结构的 STL 优先级队列无法正常工作

STL Priority queue of struct not correctly working

我在尝试将结构放入优先级队列时遇到问题,它没有按分数正确组织,如下图所示,它应该按最大数组织。

最小代码:

Class foo{
        public:
        foo();
        // this is in the .h file
        struct individuo{
            individuo(){}
            individuo(QColor cor): gene(cor){}
            QColor gene;
            int score;
            int probabilidade;
            int epoca;
        };

        // this is in the .h file
        struct Comparador{
          bool operator()(const individuo* arg1,const individuo* arg2) const {
            return arg1->score < arg2->score;
          }
        };
        void function();
        priority_queue<individuo *,vector<individuo *>, Comparador> individuos;
};

    void foo::function(){
            individuo *a = new individuo(QColor(r,g,b));
            a->score = rand() % 255;
            individuos.push(a);
    }

这是它在内存中的组织方式:

可能会发现结构没有按分数正确组织,为什么?

如果您只想让 individuo struct 按分数排序,请使用 std::map 并以分数为键。 priority_queue 用于不同的目的。

A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.

编辑:或者,只需将结构放在 std::vectorstd::array 中,然后在其上使用 std::sort

优先级队列没有用于迭代元素的接口是有原因的,它与它提供的核心服务无关。屏蔽实现允许更有效的选择。

A std::priority_queue 仅公开 push/pop/top,因此可以用堆实现它。它可以很容易地用 std::push_heapstd::pop_heap 而不是 std::vector 重写,并且不需要维护一个完全有序的元素列表来提供服务。