STL算法(四)

4.数据的排序
对于list容器中元素的排序可以使用其成员函数sort(),对于数组或者vector等具有随机访问特性的容器可以使用 STL算法sort()。下面以STL算法sort()为例进行讨论。
(1)内置数据类型的排序
对于内置数据类型的数据,sort()默认以less(小于关系函数)作为关系函数实现递增排序,为了实现递减排序,需要调用头文件中定义的greater类模板。例如,以下程序使用greater()实现vector容器中元素的递减排序( 其中sort(myv.begin(),myv.end(),less())语句等同于 sort(myv.begin(),myv.end()),实现默认的递增排序):

#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
using namespace std;
void disp(vector<int>&myv)
{ 	vector<int>::iterator it;
for(it=myv.begin();it!=myv.end();it++)
	cout<<*it<<endl;
	}
	void main(){
	int a[]={2,1,5,4,3};
	int n=sizeof(a)/sizeof(a[0]);
	vector<int>myv(a,a+n);
	cout<<"初始化myv:";disp(myv);//输出: 2 1  5 4 3
	sort<myv.begin(),myv.end(),less<int>());
	cout<<"递增排序:";disp(myv);//输出:1 2 3 4 5
	 	sort<myv.begin(),myv.end(),grater<int>());
cout<<"递减排序:";disp(myv);//输出 5 4 3 2 1
}

(2)自定义数据类型的排序
对于自定义的数据类型( 如结构体数据),同样默认以less(即小于关系函数)作为关系函数,但需要重载函数。在这些重载函数或者关系函数中指定数据的排序顺序(按哪些结构体排序,是递增还是递减)。
归纳起来,实现排序主要有两种方式:
方式1:在声明结构体类型中重载<运算符,以实现按指定成员的递增或者递减排序。例如sort(myv.begin(),myv.end())调用默认<运算符对myv容器中的所有元素实现排序。
方式2:用户自定义关系函数,以实现按指定成员的递增或递减排序,例如sort(myv.begin,myv.end(),Cmp())调用Cmp的()运算符对myv中的所有元素进行排序。
例如:有以下程序采用上述两种方式分别实现vector容器myv中的数据按no成员递减排序和按name成员递增排序:

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
struct Stud{
	int no;
	string name;
	Stud(int no1, string name1)//构造函数
	{
		no = no1;
		name = name1;
	}
	bool operator<(const Stud &s)const//方式1:重载<运算符
	{
		return s.no < no;//用于按no递减排序,将<改为>,则按no递增排序
	}
};
struct Cmp//定义关系函数
{
	bool operator()(const Stud &s,const Stud &t)const
	{
		return s.name < t.name;//用于按name递增排序,将<改为>则按name递减排序
	}
};
void Disp(vector<Stud>&myv)//输出vector的元素
{
	vector<Stud>::iterator it;
	for (it = myv.begin(); it != myv.end(); it++)
		cout << it->no << "," << it->name << "\t";
	cout << endl;
}
void main(){
	Stud a[] = { Stud(2, "Marry"), Stud(1, "John"), Stud(3, "Smith") };
	int n = sizeof(a) / sizeof(a[0]);
	vector<Stud>myv(a, a + n);
	cout << "初始myv:"; Disp(myv);//输出初始结构体数组
	sort(myv.begin(), myv.end());//默认使用小于运算符
	cout << "按no递减排序:"; Disp(myv);
	sort(myv.begin(), myv.end(), Cmp());//使用Cmp中的()运算符进行排序
	cout << "按name递增排序:"; Disp(myv);//输出: 1, John,2, Marry,3, Smith
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_42403069/article/details/86482136