【发布时间】:2021-03-24 16:16:31
【问题描述】:
我们知道std::priority_queue 可用于创建最大堆。如果我将std::pair 放入其中,则应根据 std::pair 定义通过比较第一个元素然后下一个元素对其进行排序:
template<class _Ty1,
class _Ty2> inline
constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left < _Right for pairs
return (_Left.first < _Right.first ||
(!(_Right.first < _Left.first) && _Left.second < _Right.second));
}
但是,下面的代码有奇怪的行为。
vector<int> B{13,25,32,11};
priority_queue<pair<int, int>> Q;
for (int i = 0; i < B.size(); ++i)
Q.emplace(B[i], i);
【问题讨论】:
-
The numbers of Q are not ordered. WHY!?因为最大堆没有(完全)有序。
标签: c++ priority-queue std-pair