堆,优先队列,头文件和队列是同一个#include
#include#include using namespace std; int main() { //最大堆 queue max_heap;//默认就是最大堆 queue ,less > max_heap1; //完整版 //最小堆 queue ,greater > min_heap; return 0; }
//操作 .size() .top() //堆顶元素 .pop() //堆顶元素pop掉 .push(int x) .emplace(int x) //加入一个元素
用最大堆和最小堆进行排序
#include#include #include using namespace std; int main() { vector nums{5, 1, 2, 3, 6, 4, 2, 3, 7, 8, 5, 4, 6, 9, 2, 3}; priority_queue , greater > min_heap; priority_queue , less > max_heap; for (int i = 0; i < nums.size(); i++) { min_heap.emplace(nums[i]); max_heap.emplace(nums[i]); } while (!max_heap.empty()) //从大到小 { cout << max_heap.top() << " "; max_heap.pop(); } cout << endl; while (!min_heap.empty()) //从小到大 { cout << min_heap.top() << " "; min_heap.pop(); } cout << endl; return 0; }



