Problem with order when appearing from priority_queue, is this an error with std :: priority_queue

#include <functional>
#include <queue>
#include <vector>
#include <iostream>

 struct Temp
 {
   int p;
   std::string str;
 };

 struct TempCompare
 {
     bool operator()(Temp const & a, Temp const & b)
     {
         return a.p > b.p;
     }
 };

int main() {

    std::priority_queue<Temp, std::vector<Temp>, TempCompare> pq;
    //Enable and Disable the following line to see the different output
    //{Temp t; t.p=8;t.str="str1";pq.push(t);} 
    {Temp t; t.p=8;t.str="str2";pq.push(t);}
    {Temp t; t.p=9; t.str="str1";pq.push(t);}
    {Temp t; t.p=9; t.str="str2";pq.push(t);}

    while(!pq.empty())
    {
        std::cout << pq.top().p << " " << pq.top().str << std::endl;
        pq.pop();
    }
}

Run the above program with turning the fourth line on and off in the main line; The output you get when disconnected is

8 str2
9 str1
9 str2

while when you turn it on you get

8 str1
8 str2
9 str2
9 str1

Should the behavior be consistent?

+4
source share
1 answer

No. There is no reason why behavior should be consistent. Temp{9, "str1"}and Temp{9,"str2"}are equal depending on your comparison function, so they are returned in random order. Adding different elements to the queue is likely to change this order.

, , . -

     bool operator()(Temp const & a, Temp const & b)
     {
         return std::tie(a.p,a.str) > std::tie(b.p,b.str);
     }

" p, str", .

+8

Source: https://habr.com/ru/post/1682325/


All Articles