Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中使用排序字典在优先级队列中出列#_C#_Dictionary_Priority Queue_Sorteddictionary - Fatal编程技术网

C# 在C中使用排序字典在优先级队列中出列#

C# 在C中使用排序字典在优先级队列中出列#,c#,dictionary,priority-queue,sorteddictionary,C#,Dictionary,Priority Queue,Sorteddictionary,我有一本分类词典,其形式如下: SortedDictionary<PriorityType, List<T>> dictionary; 请帮助我改进这个方法 注意:Dequeue()方法应该删除并返回具有最高优先级的对象,该对象位于具有相同优先级的其他元素之前。好的,因此我可以修改上述代码以适合我的出列操作 public T Dequeue() { var highestPriorityList = dictionary[dictionary.K

我有一本分类词典,其形式如下:

SortedDictionary<PriorityType, List<T>> dictionary;
请帮助我改进这个方法


注意:Dequeue()方法应该删除并返回具有最高优先级的对象,该对象位于具有相同优先级的其他元素之前。

好的,因此我可以修改上述代码以适合我的出列操作

public T Dequeue()
    {
        var highestPriorityList = dictionary[dictionary.Keys.First()];
        if (highestPriorityList.Count == 0)
        {
            dictionary.Remove(dictionary.Keys.First());
        }
        var topElement = highestPriorityList.First();
        highestPriorityList.Remove(topElement);
        return topElement;
    }

现在,我可以在没有InvalidOperationException的情况下随意退出队列,InvalidOperationException是由RemoveAt操作后列表中缺少的元素引起的

在将元素添加到字典之前,您是否可以检查列表中是否有元素?与其将逻辑添加到出列中,为什么不使用一个将其排序的
Add()
。但是排序后的字典不应该自动对特定键中的值进行排序吗?不,
SortedDictionary
是按键排序的。
public T Dequeue()
    {
        var highestPriorityList = dictionary[dictionary.Keys.First()];
        if (highestPriorityList.Count == 0)
        {
            dictionary.Remove(dictionary.Keys.First());
        }
        var topElement = highestPriorityList.First();
        highestPriorityList.Remove(topElement);
        return topElement;
    }