【发布时间】:2018-01-01 23:24:10
【问题描述】:
#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
行为是否应该保持一致?
【问题讨论】:
-
是否有文档表明对于相等元素的排序是“稳定的”?如果不是,则该行为似乎是可能的,但不一定是您所期望的。
-
有稳定的排序算法,比如
std::stable_sort,但是heapsort is not one of them。
标签: c++ c++11 stl std priority-queue