Search code examples
c++structstlpriority-queue

STL Priority queue of struct not correctly working


I'm having a problem while trying to put structs in a priority queue, it is not correctly organizing by the score as shown in the image below, it should be organized by the biggest number.

Minimal code:

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);
    }

and here its how it gets organized in memory:

memory

it's possible to see that the structs are not being correctly organized by its score, why?


Solution

  • If you just want the individuo struct to be sorted by the score, use std::map with the score as the key. priority_queue is used for a different purpose.

    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.

    EDIT: Alternatively, just put the struct in a std::vector or an std::array and use std::sort on it.