赞
踩
2020年9月10日 周四 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
题外话:今天是教师节,祝天下所有的老师节日快乐~~
在使用STL中很多涉及比较的函数(比如:sort
、priority_queue
、map
、set
)的时候,我们都可以自定义比较函数,具体来说大致有下面几种方法:
lambda
表达式其中,方法1
和方法2
对sort
、priority_queue
、map
、set
基本是通用的,至于方法3
和方法4
,算法sort
(包括其它排序函数,下同)可直接使用,而对于其它几种容器就需要稍微进行改动。这些使用方法再加上const
,总让人傻傻分不清,所以这里特地总结一下。
案例:Node
类有两个成员变量——a
和b
,使用sort()
算法对数组中的Node
类进行排序:成员变量x
大的排在前面(优先级低);x
相等时,y
大的排在前面。下面代码展示了使用sort()
时的4种自定义比较函数。
/** * @Copyright (C) 2020 March. All rights reserved. * @license GNU General Public License (GPL) * @author March * @email 345916208@qq.com * @function 对数组中的Node类进行排序:成员变量x大的排在前面(优先级低);x相等时,y大的排在前面 * @brief 展示使用sort()时的4种自定义比较函数 * @date 2020-09-12 */ #include <iostream> #include <queue> using namespace std; class Node { private: int x_, y_; public: Node(int x = 0, int y = 0) :x_(x), y_(y) { } // 1.重载"<"运算符(写在类内部) bool operator<(const Node& a)const { // 返回true,表示this的优先级小于a // x大的排在前面;x相同时,y大的排在前面 if (x_ == a.x_) return y_ > a.y_; return x_ > a.x_; } // 2.重写仿函数(写在类内部) bool operator()(Node& a, Node& b) const { // 返回true,表示this的优先级小于a // x大的排在前面;x相同时,y大的排在前面 if (a.get_x() == b.get_x()) return a.get_y() > b.get_y(); return a.get_x() > b.get_x(); } // 获取x_和y_的值 int get_x() { return x_; }; int get_y() { return y_; }; // 打印函数 void print() { cout << x_ << " " << y_ << endl; } }; // 1.重载"<"运算符(写在类外部) bool operator
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。