温馨提示×

c++ priority_queue的迭代器使用

c++
小樊
82
2024-09-04 19:15:09
栏目: 编程语言

std::priority_queue 是 C++ 标准库中的一个容器适配器,它提供了对元素进行排序和访问的功能

然而,如果你需要遍历 std::priority_queue 中的所有元素,可以通过以下方法实现:

  1. std::priority_queue 中的元素移动到一个临时的容器(例如 std::vector)中。
  2. 对临时容器进行排序(如果需要)。
  3. 使用迭代器遍历临时容器。

这里有一个示例:

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

int main() {
    std::priority_queue<int> pq;
    pq.push(5);
    pq.push(8);
    pq.push(3);
    pq.push(1);

    // 将 priority_queue 中的元素移动到 vector 中
    std::vector<int> temp_vec;
    while (!pq.empty()) {
        temp_vec.push_back(pq.top());
        pq.pop();
    }

    // 对 vector 进行排序(从小到大)
    std::sort(temp_vec.begin(), temp_vec.end());

    // 使用迭代器遍历 vector
    for (auto it = temp_vec.begin(); it != temp_vec.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}

这段代码首先将 std::priority_queue 中的元素移动到一个 std::vector 中,然后对 std::vector 进行排序,最后使用迭代器遍历 std::vector。注意,这种方法会改变 std::priority_queue 的内部状态,因为我们在将元素移动到 std::vector 时会不断地调用 pop() 函数。如果你需要保留原始的 std::priority_queue,可以在操作之前创建一个副本。

0