Files
Data-Structure/STL/STL-priority_queue/main.cpp
2025-08-12 23:00:31 +08:00

43 lines
1.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <queue>
#include <functional>
#include <iostream>
using namespace std;
bool cmp(const int& a, const int& b) {
return a < b;
}
class compare {
public:
template <typename T>
bool operator()(const T& a, const T& b) {
//返回大的,泛型不能直接返回指针,没有初始化
//用struct或者class套一下在class初始化的过程中就顺带着初始化了
return a < b;//false是向上swap
}
};
int main() {
auto cmpl = []<class T>(const T& a, const T& b) {
return a < b;
};
//priority_queue<int, deque<int>, decltype(cmpl)> pq(cmpl);合法
//priority_queue<int, deque<int>, bool(*)(const int&, const int&)> pq(cmp);合法
priority_queue<int, deque<int>, compare> pq;
//上面三种写法非常重要
pq.push(1);
pq.push(2);
pq.push(6);
pq.push(3);
pq.push(7);
pq.push(4);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
return 0;
}
/*
7 6 4 3 2 1
*/