C++,优先队列,项目不排序

标签 c++ sorting priority-queue

优先队列有问题:

std::priority_queue <NodePrio, std::vector<NodePrio>, sortNodesByPrio> PQ;

在哪里

struct NodePrio
{
Node *node;
double priority;

NodePrio() : node(NULL), priority(0) {}
NodePrio(Node *node_, double priority_) : node(node_), priority(priority_) {}
};

class sortNodesByPrio
{
public:
    bool operator () (const NodePrio &n1, const NodePrio  &n2)   const;
}


bool sortNodesByPrio::operator () (const NodePrio &n1, const NodePrio &n2) const
{
return n1.priority < n2.priority;
}

反复推送新元素后

PQ.push(NodePrio(node, distance));

并且从任何时间点开始它们都没有排序(见下文)...我尝试调试代码,比较器代码已重复执行...

Step1: 
push (node, 55.33);

PQ:
[0] 55.33

Step2:
push (node, 105.91);

PQ:
[0] 105.91
[1] 55.33

Step 3:
push (node, 45.18);

PQ:
[0] 105.91
[1] 55.33
[2] 45.18

Step 4:
push (node, 70.44);

PQ:
[0] 105.91
[1] 70.44
[2] 45.18
[3] 55.33   //Bad sort

最佳答案

根据您显示的“示例结果”,您似乎不了解什么是优先级队列。

优先队列保证当您从其中移除元素时(使用top()pop()),元素将按优先顺序被移除。元素不按优先顺序存储,它们存储在堆中。

您可以查阅您最喜欢的算法书籍或网站,了解有关优先队列如何存储其元素的更多信息。

关于C++,优先队列,项目不排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4287716/

相关文章:

c++ - 通过套接字发送 HBITMAP

sorting - 聚合 Elasticsearch 中存储桶的字符串排序

c++ - 清理映射中所有共享指针的正确方法是什么?

c# - 同时排序/从列表中删除数据

将 char 指针数组的值复制到结构中

JAVA-PriorityQueue实现

具有自定义匿名比较器的 Java 优先级队列

c++ - 使用 std::greater

c++ - 在cpp中使用unix系统调用

c++ - 关于 Armadillo 稀疏矩阵中的内存分配