大佬教程收集整理的这篇文章主要介绍了STL priority_queue自定义排序实现方法详解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include<iostream> #include<queue> using namespace std; //函数对象类 template <typename T> class cmp { public: //重载 () 运算符 bool operator()(T a,T b) { return a > b; } }; int main() { int a[] = { 4,2,3,5,6 }; priority_queue<int,vector<int>,cmp<int> > pq(a,a+5); while (!pq.empty()) { cout << pq.top() << " "; pq.pop(); } return 0; }运行结果为:
2 3 4 5 6
注意,C++ 中的 struct 和 class 非常类似,前者也可以包含成员变量和成员函数,因此上面程序中,函数对象类 cmp 也可以使用 struct 关键字创建:struct cmp { //重载 () 运算符 bool operator()(T a,T b) { return a > b; } };可以看到,通过在 cmp 类(结构体)重载的 () 运算符中自定义排序规则,并将其实例化后作为 priority_queue 模板的第 3 个参数传入,即可实现为 priority_queue 容器适配器自定义比较函数。
template <typename T> struct less { //定义新的排序规则 bool operator()(const T &_lhs,const T &_rhs) const { return _lhs < _rhs; } };std::greater<T> 的底层实现代码为:
template <typename T> struct greater { bool operator()(const T &_lhs,const T &_rhs) const { return _lhs > _rhs; } };可以看到,std::less<T> 和 std::greater<T> 底层实现的唯一不同在于,前者使用 < 号实现从大到小排序,后者使用 > 号实现从小到大排序。
#include<queue> #include<iostream> using namespace std; class node { public: node(int x = 0,int y = 0) :x(X),y(y) {} int x,y; }; //新的排序规则为:先按照 x 值排序,如果 x 相等,则按 y 的值排序 bool operator < (const node &a,const node &b) { if (a.x > b.X) return 1; else if (a.x == b.X) if (a.y >= b.y) return 1; return 0; } int main() { //创建一个 priority_queue 容器适配器,其使用默认的 vector 基础容器以及 less 排序规则。 priority_queue<node> pq; pq.push(node(1,2)); pq.push(node(2,2)); pq.push(node(3,4)); pq.push(node(3,3)); pq.push(node(2,3)); cout << "x y" << endl; while (!pq.empty()) { cout << pq.top().x << " " << pq.top().y << endl; pq.pop(); } return 0; }输出结果为:
x y
1 2
2 2
2 3
3 3
3 4
class node { public: node(int x = 0,y; bool operator < (const node &b) const{ if ((*this).x > b.X) return 1; else if ((*this).x == b.X) if ((*this).y >= b.y) return 1; return 0; } };
class node { public: node(int x = 0,y; friend bool operator < (const node &a,const node &b); }; //新的排序规则为:先按照 x 值排序,如果 x 相等,则按 y 的值排序 bool operator < (const node &a,const node &b){ if (a.x > b.X) return 1; else if (a.x == b.X) if (a.y >= b.y) return 1; return 0; }总的来说,以函数对象的方式自定义 priority_queue 的排序规则,适用于任何情况;而以重载 > 或者 < 运算符间接实现 priority_queue 自定义排序的方式,仅适用于 priority_queue 中存储的是结构体变量或者类对象(包括 String 类对象)。
以上是大佬教程为你收集整理的STL priority_queue自定义排序实现方法详解全部内容,希望文章能够帮你解决STL priority_queue自定义排序实现方法详解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。