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.

  • 30
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值