如何迭代priority_queue?

新手上路,请多包涵

我可以使用迭代器(如 vector )在 C++ 中遍历标准 priority_queue 或标准 queue 吗?我不想使用 pop 因为它会导致我的队列出队。

谢谢你的帮助

原文由 mina70 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 473
1 个回答

制作副本并对其进行迭代 - 由@lie-ryan 建议

#include <iostream>
#include <queue>

using namespace std;
void make_copy(priority_queue<int, vector<int>> pq, vector<int> &arr)
{
    arr = {}; // if it was not empty , make it :)
    while (!pq.empty())
    {
        arr.push_back(pq.top());
        pq.pop();
    }
}
int main()
{
    priority_queue<int, vector<int>> q;
    q.push(1);
    q.push(2);
    q.push(3);
    vector<int> arr;
    make_copy(q, arr); // this will copy all elements of q to arr :)
    for (auto &x : arr)
    {
        cout << x << " ";
    }
}

原文由 Kushal Nagwanshi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏