将值添加到队列列表中的特定位置

本文关键字:定位 位置 列表 添加 队列 | 更新日期: 2023-09-27 18:34:43

Queues:

    public class Queue
    {
        public Queue() { }
        public process Front() { return this.q_list.ElementAt(0); }
        public int Size { get { return this.q_list.Count; } }
        public bool IsEmpty { get { return this.q_list.Count <= 0 ? true : false; } }
        public void Enqueue(process proc) { this.q_list.Add(proc); } 
        public void Dequeue() { this.q_list.RemoveAt(0); }
        public List<process> q_list = new List<process>();
    };

创建列表:

    List<Queue> rr_list = new List<Queue>(); 

流程结构:

    public class process
    {
        public int Proc_a;
        public int Proc_b;
        public int Proc_Index;
    };

假设我想根据Proc_Index的值将一个进程添加到特定位置的列表。 我该怎么做? 我们还假设列表最初是空的。

    process proc = new process{
         Proc_a = 1,
         Proc_b = 2,
         Proc_Index = 4 };

我想将其添加到位于索引 4 的列表中的队列中。

这可能吗?

我试过:

rr_list[proc.Proc_Index].Enqueue(proc); 

但它说找不到索引或其他问题。

我唯一能做的就是通过为多达 20 个索引添加空队列来初始化列表,但我不知道是否有更好的方法。

将值添加到队列列表中的特定位置

你应该

使用System.Collections.Generic.Queue而不是自己编写。如果要查找键值,请使用System.Collections.Generic.Dictionary

var rr_list = new Dictionary<int, Queue<process>>();
process proc = new process{
     Proc_a = 1,
     Proc_b = 2,
     Proc_Index = 4 };
rr_list[proc.Proc_Index].Enqueue(proc); 

您可能希望使用字典而不是列表。

var rr_list = new Dictionary<int, Queue>(); 

然后有一个这样的添加进程函数

function void AddProcess(proccess proc){
     if(rr_list.ContainsKey(proc.Proc_Index){
        rr_list[proc.Proc_Index].Enqueue(proc);
     } else {
        rr_list[proc.Proc_Index] = (new Queue()).Enqueue(proc); 
     }
}

列表通常应该没有孔,因此如果要将索引 4 处的元素添加到空列表中,这将使索引 0 到 3 包含 null。

现在,你可以这样做。您可以检查长度是否大于请求的索引,如果没有,请继续添加 null 值,直到它大于。然后索引就会存在,你可以给它分配一些东西:

static void EnsureLength<T> (List<T> list, int index)
{
    while (list.Count <= index)
        list.Add(default(T));
}

然后你可以像这样使用它:

List<int?> list = new List<int?>();
EnsureLength(list, 3);
list[3] = 123;

一个可能更好的方法是简单地使用字典,特别是如果你知道你会有漏洞。所以你只会有一个Dictionary<int, T>

Dictionary<int, int?> dict = new Dictionary<int, int?>();
dict[3] = 123;