c++ - 从 priority_queue 弹出时出现排序问题,这是 std::priority_queue 的错误吗

标签 c++ c++11 stl 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();
    }
}

运行上面的程序,启用和禁用main中的第四行;禁用时得到的输出是

8 str2
9 str1
9 str2

而当它启用时你会得到

8 str1
8 str2
9 str2
9 str1

行为不应该一致吗?

最佳答案

没有。行为没有理由保持一致。 Temp{9, "str1"}Temp{9,"str2"} 根据您的比较函数是相等的,因此它们以任意顺序返回。向队列中添加不同的元素很可能会改变该顺序。

如果希望它们以一致的顺序返回,则需要扩展比较功能。最简单的方法是

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

如果你想“在 p 中下降,但在 str 中上升”,你必须自己做。

关于c++ - 从 priority_queue 弹出时出现排序问题,这是 std::priority_queue 的错误吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330322/

相关文章:

c++ - 为什么 long 和 long long 的最大值产生相同的输出?

c++ - 通过引用或按值将共享指针作为参数传递给类

c++ - 在容器中查找以给定字符开头的所有单词

c++ - 测试抛出失败的函数

c++ - 使用 OpenCV 的最大熵阈值

c++ - typedef 模板的成员类型

c++ - 什么是常量无效?

C++11 std::to_string(double) - 没有尾随零

c++ - 调整多维 vector 的大小

c++ - 用于清除指针 vector 的模板函数