简体   繁体   English

C++ 优先级队列不排序

[英]C++ priority queue does not sort

I tried to implement a priority queue in C++ with a custom Class and Compare struct, but whenever I push a new element the queue doesn´t sort itself.我尝试使用自定义类和比较结构在 C++ 中实现优先级队列,但是每当我推送一个新元素时,队列不会自行排序。

In Header:在标题中:

private:
    std::priority_queue<Node*, std::vector<Node*>, NodeCompare> queue;

Struct:结构:

struct NodeCompare
{
    bool operator()(Node* n1, Node* n2) 
    {
        int val1 = n1->getValue();
        int val2 = n2->getValue();
        return val1 < val2;
    }
};

In Class:在班上:

Node* node = new Node(nrInTree, value);
queue.push_back(node);

Any ideas?有任何想法吗?

Your code is correct.你的代码是正确的。 But I think you have a misunderstanding here.但我认为你在这里有一个误解。 Because priority_queue is implemented using data structure heap.因为priority_queue 是使用数据结构堆实现的。 As we know, heap is not sorted.众所周知,堆没有排序。 It only has the property that the maximum element is at the front.它只有最大元素在前面的属性。 Every time, you insert an element into a heap, heap will use O(lgN) time to push the maximum into the front.每次向堆中插入一个元素,堆将使用 O(lgN) 时间将最大值推入最前面。 And every time you pop an element, the largest element will be obtained.而且每次弹出一个元素,都会得到最大的元素。 But heap is not sorted at all.但是堆根本没有排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM