C++仿函数(四)排序

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

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

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

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

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

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

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

我们写段代码测试下吧

void useFunctorInSort() {
	set myset;
	for (int t = 0; t < 20; t++) {
		myset.insert(t);
	}
	set> lessSet;
	for (int t = 0; t < 20; t++) {
		lessSet.insert(t);
	}
	set> greaterSet;
	for (int t = 0; t < 20; t++) {
		greaterSet.insert(t);
	}
	copy(myset.begin(),myset.end(),ostream_iterator(cout, " "));
	cout << endl;
	copy(lessSet.begin(), lessSet.end(), ostream_iterator(cout, " "));
	cout << endl;
	copy(greaterSet.begin(), greaterSet.end(), ostream_iterator(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 lsSet;
	lsSet.insert(12);
	lsSet.insert(32);
	lsSet.insert(91);
	lsSet.insert(66);
	copy(lsSet.begin(), lsSet.end(), ostream_iterator(cout, " "));
	cout << endl;
}

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

你可能感兴趣的:(C++仿函数(四)排序)