首页 > 编程语言 > 详细

C++仿函数(四)排序

时间:2020-04-29 19:36:27      阅读:75      评论:0      收藏:0      [点我收藏+]

https://www.cnblogs.com/cyssmile/p/12791302.html
在这里我们谈到了functor可以用于在容器中定义排序方式。

这里在讲到一个简单的例子:

set<int> myset = {1,2,3,4,9,5};

这种方式与下面这种方式定义是相同的.

set<int, less<int>> myset = {1,2,3,4,9,5};

那么如何定义一个由大到小排序的set呢

set<int, greater<int>> myset = {1,2,3,4,9,5};

我们写段代码测试下吧

void useFunctorInSort() {
	set<int> myset;
	for (int t = 0; t < 20; t++) {
		myset.insert(t);
	}
	set<int,less<int>> lessSet;
	for (int t = 0; t < 20; t++) {
		lessSet.insert(t);
	}
	set<int, greater<int>> greaterSet;
	for (int t = 0; t < 20; t++) {
		greaterSet.insert(t);
	}
	copy(myset.begin(),myset.end(),ostream_iterator<int>(cout, " "));
	cout << endl;
	copy(lessSet.begin(), lessSet.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	copy(greaterSet.begin(), greaterSet.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
}

技术分享图片

我们自定义一个排序方式

1、 先比较个位,个位小在前
2、 个位相等,按照数的大小排序

来我们写代码吧

struct ls_less
{
	bool operator ()(const int& x,const int& y) {
		if ((x % 10) != (y % 10)) {
			return (x % 10) < (y % 10);
		}
		else {
			return x < y;
		}
		
	}
};

void testLsLess() {
	set<int, ls_less> lsSet;
	lsSet.insert(12);
	lsSet.insert(32);
	lsSet.insert(91);
	lsSet.insert(66);
	copy(lsSet.begin(), lsSet.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
}

技术分享图片

本节代码地址:
https://github.com/cyssmile/cplus/tree/master/STLLearningNote/STLLearningNote

C++仿函数(四)排序

原文:https://www.cnblogs.com/cyssmile/p/12803878.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!