c++容器 set 自定义排序

set c++ reference是c++中的一种容器,set可以用二叉树搜索树实现,set有两个特点:

1. set中的元素不允许重复;

2. set内部会维护一个严格的弱排序关系。

上述两个特点实际上都依赖set的compare函数,compare函数判断两个元素相等就是相等,与元素本身没有直接的关系。

默认定义了compare函数

利用set内部默认的compare函数,可以将整数从小到大排序,将字符串按字母序进行排序。

#include <string>
#include <set>
#include <iostream>
using namespace std;

int main() {
	int a[] = {20,10,30,40,50};
	set<int> s1(a, a + 5);
	for (auto it = s1.cbegin(); it != s1.cend(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	string b[] = {"apple", "banana", "pear", "orange", "strawberry"};
	set<string> s2(b, b + 5);
	for (auto it = s2.cbegin(); it != s2.cend(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

输出:

10 20 30 40 50
apple banana orange pear strawberry

自定义排序函数

可以通过定义结构体(或类),并在其中重载()运算符,来自定义排序函数。然后,在定义set的时候,将结构体加入其中例如如下代码中的set<int, intComp>和set<string, strComp >。

#include <iostream>
#include <string>
#include <set>
using namespace std;

struct intComp {
	bool operator() (const int& lhs, const int& rhs) const{
		return lhs > rhs;
	}
};

struct strComp
{
	bool operator() (const string& str1, const string& str2) const {
		return str1.length() < str2.length();
	}
};

int main() {
	int a[] = {10, 20, 30, 40, 50};
	set<int, intComp> s1(a, a + 5);
	for (auto it = s1.cbegin(); it != s1.cend(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	string b[] = {"apple", "banana", "pear", "orange", "strawberry"};
	set<string, strComp > s2(b, b + 5);
	for (auto it = s2.cbegin(); it != s2.cend(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

输出:

50 40 30 20 10
pear apple banana strawberry

从上述程序段的输出可见,定义整型的比较函数后,输出数字按从大到小排序。定义字符串的比较函数为比较字符串的长度,输出字符串则按长度从小到大排序,其中并未出现orange了,因为banana的长度是6,而orange的长度也是6,set的构造函数认为orange与banana相同,而orange出现在后,因此不会有orange.

猜你喜欢

转载自blog.csdn.net/u012604810/article/details/79804928