C++中堆操作可通过STL算法函数和priority_queue容器适配器实现。1. 使用<al algorithm>中的make_heap、push_heap、pop_heap可在vector等容器上构建和操作堆,默认为最大堆,通过greater<int>可实现最小堆;2. priority_queue定义于<queue>头文件,封装了堆操作,使用更简便,支持自定义比较函数和结构体排序,推荐用于常规场景。

在C++中,堆操作和优先队列可以通过STL中的 算法函数 和 容器适配器 来实现。主要涉及
make_heap
push_heap
pop_heap
priority_queue
STL 提供了一组算法用于在普通容器(如 vector)上执行堆操作。这些函数定义在
<algorithm>
使用示例:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2};
    // 构建最大堆
    std::make_heap(v.begin(), v.end());
    // 输出堆顶
    std::cout << "Top: " << v.front() << "\n";  // 输出 9
    // 插入元素
    v.push_back(7);
    std::push_heap(v.begin(), v.end());
    std::cout << "New top: " << v.front() << "\n";  // 输出 9 或 7
    // 弹出堆顶
    std::pop_heap(v.begin(), v.end());
    int top = v.back();
    v.pop_back();
    std::cout << "Popped: " << top << "\n";
    return 0;
}
默认是最大堆。要实现最小堆,可以传入比较函数,比如
std::greater<int>
立即学习“C++免费学习笔记(深入)”;
std::vector<int> v = {3, 1, 4, 1, 5};
std::make_heap(v.begin(), v.end(), std::greater<int>());
v.push_back(0);
std::push_heap(v.begin(), v.end(), std::greater<int>);
priority_queue
<queue>
基本用法:
#include <queue> #include <iostream> std::priority_queue<int> max_heap; // 最大堆 max_heap.push(3); max_heap.push(1); max_heap.push(4); std::cout << max_heap.top() << "\n"; // 输出 4 max_heap.pop(); // 移除 4
std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap; min_heap.push(3); min_heap.push(1); min_heap.push(4); std::cout << min_heap.top() << "\n"; // 输出 1
struct Task {
    int priority;
    std::string name;
};
// 自定义比较:优先级小的先出(最小堆)
auto cmp = [](const Task& a, const Task& b) {
    return a.priority > b.priority;
};
std::priority_queue<Task, std::vector<Task>, decltype(cmp)> pq(cmp);
其定义为:
template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;
less
基本上就这些。直接用
priority_queue
make_heap
以上就是C++如何使用STL实现堆heap操作和priority_queue的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号