⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

std::priority_queue 堆

掌握优先队列(最大堆/最小堆)的基本操作。 · 难度:入门 · +15XP

std::priority_queue 优先队列(堆)

priority_queue 是一个容器适配器,默认使用 std::vector 实现最大堆(堆顶始终为最大元素)。通过 push() 插入元素,pop() 移除堆顶,top() 访问堆顶元素。若要得到最小堆,可指定 std::greater<T> 作为比较器。内部自动维护堆性质,适合实现任务调度、Dijkstra 算法等场景。

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

int main() { // 最大堆(默认) std::priority_queue<int> max_pq; max_pq.push(30); max_pq.push(10); max_pq.push(50); std::cout << "最大堆顶: " << max_pq.top() << ' '; // 50

// 最小堆 std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq; min_pq.push(30); min_pq.push(10); min_pq.push(50); std::cout << "最小堆顶: " << min_pq.top() << ' '; // 10

// 遍历(注意:pop 会破坏结构) while (!min_pq.empty()) { std::cout << min_pq.top() << ' '; min_pq.pop(); } // 输出: 10 30 50 return 0; }

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 105 篇
0 完成
🔥 0