12.1 STL排序算法sort

从小到大排序:

对a[]中的n个数进行排序,数组下标从1 开始 sort(a+1,a+1+n);

对a[]中的n个数进行排序,数组下标从0开始sort(a,a+n);

operator()相当于就是一个函数名,但是()不可以省略。

另一种使用方法:

比如成绩排序:

描述

给出班里某门课程的成绩单,请你按成绩从高到低对成绩单排序输出,如果有相同分数则名字字典序小的在前。

输入

第一行为n (0 < n < 20),表示班里的学生数目;
接下来的n行,每行为每个学生的名字和他的成绩, 中间用单个空格隔开。名字只包含字母且长度不超过20,成绩为一个不大于100的非负整数。

输出

把成绩单按分数从高到低的顺序进行排序并输出,每行包含名字和分数两项,之间有一个空格。

样例输入

4

Kitty 80

Hanmeimei 90

Joey 92

Tim 28

样例输出

Joey 92

Hanmeimei 90

Kitty 80

Tim 28

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
 
struct Student{
	char c[30];
	int a;
}; 
 
Student stu[30];
bool cmp1(Student x, Student y)
{
	if(x.a == y.a)
		return strcmp(x.c,y.c) < 0;//注意不能用x.c < y.c,这样就只能比较第一个字符的大小 
	else
		return x.a > y.a;
} 
 
int main()
{
	int n;
	cin >> n;
	for(int i = 1; i <= n; ++i)
	{
		cin >> stu[i].c >> stu[i].a;
	}
	sort(stu+1,stu+1+n,cmp1);
	for(int i = 1; i <= n; ++ i)
	{
		cout << stu[i].c << " " << stu[i].a << endl;
	}
	return 0;
}

参考链接:https://blog.csdn.net/yanyanwenmeng/article/details/82024970

#include<iostream>
#include<algorithm>
using namespace std;

struct rule1
{
	bool operator()(const int &a1, const int &a2)//a1排在a2前面返回true,所以为从大到小排
	{
		return a1 > a2;
	}
}; 

struct rule2
{
	bool operator()(const int &a1, const int &a2)//a1排在a2前面返回true,所以为从小到大排
	{
		return a1%10 < a2%10;
	}
};
 
int print(int a[], int n)
{
	for(int i = 0; i < n; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}

int main()
{
	int a[] = {12,45,3,98,21,7};
	int n = sizeof(a)/sizeof(int);
	sort(a,a+n); //从小到大 
	print(a,n);
	sort(a,a+n,rule1());//从大到小 
	print(a,n);
	sort(a,a+n,rule2());//又个位数从小到大 
	print(a,n);
	return 0;
}

 

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Student{//定义一个新的结构变量Student,Student相等于我们自己定义的一个新的变量,类似于int,char 
	char name[20];
	int id;
	double gpa;
};

Student a[]={{"Jack",112,3.4},{"Mary",102,3.8},{"Mary",117,3.9},{"Ala",333,3.5},{"Zero",101,4.0}};

struct rule1{//姓名从小到大 
	 bool operator()(const Student &a1, const Student &a2)
	 {
	 	if(strcmp(a1.name,a2.name) < 0)
	 		return true;
	 	return false;
	 }
};

struct rule2{//Id从小到大 
	bool operator()(const Student &a1, const Student &a2)
	{
		return a1.id < a2.id;
	}
};

struct rule3{//gpa从大到小 
	bool operator()(const Student &a1, const Student &a2)
	{
		return a1.gpa > a2.gpa;
	}
};

void print(Student a[],int n)
{
	for(int i = 0; i < n; ++ i)
	{
		cout << a[i].name << " " << a[i].id << " " << a[i].gpa << endl; 
	}
	cout << endl;
}

int main()
{
	int n = sizeof(a)/sizeof(Student);//要注意这里是sizeof(Student),而不是int,很容易犯常识性错误
	sort(a,a+n,rule1());
	print(a,n);
	sort(a,a+n,rule2());
	print(a,n);
	sort(a,a+n,rule3());
	print(a,n);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/82320023
今日推荐