STL中set和map容器设置排序函数:自定义或使用库函数

set和map容易都是关联式容器,可以实现自动排序,而其中的排序函数默认是按照从小到大的顺序(或字典序)进行排序操作,我们可以根据数据类型的不同,自己设置排序函数,进而控制set和map容器的排序和输出结果。

其中设置排序函数,可以使用库函数,也可以自行定义。

以下代码分别给出了库函数,自定义排序函数(重载()运算符)的使用方法:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <set>
#include <map>
using namespace std;

class MySetCmp
{
public:
	// 重载()操作符,记住函数后加const,表示此函数不会对数据进行修改
	// 指明了这个函数不会修改该类的任何成员数据的值,称为常量成员函数。
	bool operator()(const int& a, const int& b) const
	{
		return a > b;
	}
};

int main()
{
	// set, 从大到小排序, 使用库函数
	set<int, greater<int>> s1{ 1,2,3,4 };
	cout << "s1 : ";
	for (auto i : s1)
	{
		cout << i << " ";  // 4 3 2 1 
	}
	cout << endl;
	
	// set, 从大到小排序, 使用自定义函数
	set<int, MySetCmp> s2{ 1,2,3,4 };
	cout << "s2 : ";
	for (auto i : s2)
	{
		cout << i << " ";  // 4 3 2 1 
	}
	cout << endl;

	// map, 根据key值,从大到小排序, 使用库函数
	map<int, int, greater<int>> m1{ {1,4},{2,3},{3,2},{4,1} };
	cout << "m1 : ";
	for (auto i : m1)
	{
		cout << i.first << " ";  // 4 3 2 1 
	}
	cout << endl;

	// map, 根据key值,从大到小排序, 使用库函数
	map<int, int, MySetCmp> m2{ {1,4},{2,3},{3,2},{4,1} };
	cout << "m2 : ";
	for (auto i : m2)
	{
		cout << i.first << " ";  // 4 3 2 1 
	}
	cout << endl;

	return 0;
}

函数执行结果:

s1 : 4 3 2 1
s2 : 4 3 2 1
m1 : 4 3 2 1
m2 : 4 3 2 1

C++还提供了其它比较函数可供使用,比如:

  1. less():小于
  2. less_equal():小于等于
  3. greater():大于
  4. greater_equal():大于等于
  5. equal(): 等于

等等,其它函数。

另外,对于自定义类型的数据,我们一般都需要自行定义比较函数来进行排序操作,因此我们可以根据自定义数据的特点,去重载()运算符,然后在函数内部实现自己的比较逻辑。

谢谢阅读。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章