- 1、默认排序
使用默认定义优先队列,将以最大堆的形式进行存储;
//实例
vector<int> nums{1, 2, 3, 4, 5};
priority_queue<int> heap;
for (int num : nums) {
heap.emplace(num);
}
while (!heap.empty()) {
cout << heap.top() << " ";
heap.pop();
}
/*
输出为
6 5 4 3 2 1
*/
- 2、使用提供的
greater
和less
函数排序- 使用
greater
进行排序,将以最小堆的形式进行存储; - 使用
less
进行排序,将以最大堆的形式进行存储;
- 使用
//实例
vector<int> nums{1, 2, 3, 4, 5};
//greater函数
priority_queue<int, vector<int>, greater<int>> heap1;
for (int num : nums) {
heap1.emplace(num);
}
while (!heap1.empty()) {
cout << heap1.top() << " ";
heap1.pop();
}
/*
输出为
1 2 3 4 5 6
*/
//less函数
priority_queue<int, vector<int>, less<int>> heap2;
for (int num : nums) {
heap2.emplace(num);
}
while (!heap2.empty()) {
cout << heap2.top() << " ";
heap2.pop();
}
/*
输出为
6 5 4 3 2 1
*/
-
3、使用自定义的比较函数
-
直接定义比较函数;
//实例
bool cmp(int& a, int& b) {
return a < b; //最大堆写法
}
vector<int> nums{1, 2, 3, 4, 5};
priority_queue<int, vector<int>, decltype(&cmp)> heap(cmp);
for (int num : nums) {
heap.emplace(num);
}
while (!heap.empty()) {
cout << heap.top() << " ";
heap.pop();
}
/*
输出为
6 5 4 3 2 1
*/
- 进行函数重载;
//实例
struct cmp {
bool operator() (int& a, int& b) {
return a < b; //最大堆写法
}
};
vector<int> nums{1, 2, 3, 4, 5};
priority_queue<int, vector<int>, cmp> heap;
for (int num : nums) {
heap.emplace(num);
}
while (!heap.empty()) {
cout << heap.top() << " ";
heap.pop();
}
/*
输出为
6 5 4 3 2 1
*/