c++ 中的容器 优先队列(priority_queue) 主要有两种排列方式 默认的less 和 greater
less 表示容器中的数据是 由大到小进行排列的
greater 表示容器中的数据是 由小到大进行排列的
那么也就意味着 less模式下,优先输出的较大的数值, greater模式下优先输出的较小的数值;
如下示例:
#include <functional> #include <queue> #include <vector> #include <iostream> template<typename T> void print_queue(T& q) { while(!q.empty()) { std::cout << q.top() << " "; q.pop(); } std::cout << '\n'; } int main() { std::priority_queue<int> q; for(int n : {1,8,5,6,3,4,0,9,7,2}) q.push(n); print_queue(q); std::priority_queue<int, std::vector<int>, std::greater<int> > q2; for(int n : {1,8,5,6,3,4,0,9,7,2}) q2.push(n); print_queue(q2); }
输出:
9 8 7 6 5 4 3 2 1 0 // less 0 1 2 3 4 5 6 7 8 9 //greater
可以对自定义操作符(>或 <)
struct node { bool operator< (const node n1, const node n2) { return n1.priority < n2.priority; } int priority; int value; }; struct node { bool operater < (const struct node &k) const{ priority < k.priority; } int priority, value; } //两种自定义方式是等价的