【问题标题】:How to make max heap filled with std::pair in C++如何在 C++ 中使最大堆充满 std::pair
【发布时间】: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);

Q 的数量是无序的。为什么!? Q 显示在

【问题讨论】:

  • The numbers of Q are not ordered. WHY!? 因为最大堆没有(完全)有序。

标签: c++ priority-queue std-pair


【解决方案1】:

它们是有序的。您的 IDE 正在向您显示优先级队列下的向量中对的顺序。参见例如Wikipedia 关于堆通常如何以数组形式表示,以了解它们为什么以这种确切的顺序出现。如果您实际上将队列中的元素一一弹出,则将以正确的顺序返回:

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

int main() {
  std::vector<int> B{13,25,32,11};
  std::priority_queue<std::pair<int, int>> Q;
  for (int i = 0; i < B.size(); ++i)
    Q.emplace(B[i], i);

  while (!Q.empty()) {
    auto P(Q.top());
    Q.pop();

    std::cout << P.first << ", " << P.second << '\n';
  }
}

将打印:

32, 2
25, 1
13, 0
11, 3

【讨论】:

  • 这就是我想要的。优先队列的底层数据结构是堆。堆是用向量表示的二叉树。例如。第一个元素大于优先级队列中的第二个和第三个元素。第二个和第三个没有大小关系。感谢您的回复。
【解决方案2】:

deduction changed in c++20 - 你可以用 c++17 编译它,你的代码就可以工作了。您必须根据 cpp20 指南解析您的代码。

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2019-02-05
    • 2011-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2011-08-01
    相关资源
    最近更新 更多