从priority_queue弹出时出现排序问题,这是 std::p riority_queue 的错误吗?
Ordering issue while popping from priority_queue, Is this a bug 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();
}
}
运行上述程序,启用和禁用主中的第四行;禁用时获得的输出是
8 str2
9 str1
9 str2
而当它启用时,你会得到
8 str1
8 str2
9 str2
9 str1
行为不应该是一致的吗?
No. 行为没有理由保持一致。 根据比较函数,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
上升",你必须自己做。
相关文章:
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- C++ queue.front();为什么不从第一个元素开始呢?
- 我可以擦除 std::queue 中间的节点吗?
- 获取大小时是否必须锁定 std::queue?
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- 销毁 std::queue 会导致内存错误
- 如何将一个 std::queue 的内容附加到另一个
- 使用元素加载 std::queue<uint8_t*> 的更有效方法?
- 为什么 std::queue 没有实现 insert() 而 std::d eque 实现了?
- 带有 std::vector 和 std::queue 的 Prim's 算法,我的代码有什么问题?
- C++程序在 #include 时无法编译<stack>,#include<queue>
- 是boost :: lockfree :: Queue(在多线程程序中)可锁定
- std :: queue :: pop()在其std :: unique_ptr数据上操作
- 通过 std::queue 中的元素的值获取元素的索引
- 如何索引指向数组 [queue] 的指针数组
- 像std::queue这样的c++标准库容器是否保证是可重入的
- 在 boost::lockfree:queue 默认构造函数的情况下断言失败
- 将元素推入 std::queue 时避免复制
- 连接两个C 文件(list.cc and queue.cc)困难