要使用STL中的算法,需要在程序头文件引入#include <algorithm>
1.对基本类型的数组从小到大排序:
sort(数组名+n1,数组名+n2);
n1和n2都是int类型的表达式,可以包含变量
如果n1=0,则 + n1可以不写
将数组中下标范围为[n1,n2)的元素从小到大排序。下标为n2的元素不在排序区间内
2.对元素类型为T的基本类型数组从大到小排序:
sort(数组名+n1,数组名+n2,greater<T>());
3.用自定义的排序规则,对任何类型T的数组排序
sort(数组名+n1,数组名+n2,排序规则结构名());
排序规则结构的定义方式:
struct 排序规则结构名 { bool operator()( const T & a1,const T & a2) {
//若a1应该在a2前面,则返回true,否则返回false。
}
};
例1:
int a[] = {15,4,3,9,7,2,6}; sort(a,a+7); //对整个数组从小到大排序
int a[] = {15,4,3,9,7,2,6}; sort(a,a+3); // 结果:{3,4,15,9,7,2,6}
int a[] = {15,4,3,9,7,2,6}; sort(a+2,a+5); //结果:{15,4,3,7,9,2,6}
例2:
int a[] = {15,4,3,9,7,2,6};
sort(a+1,a+4,greater<int>()); // 结果:{15,9,4,3,7,2,6}
例3:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct Student {
char name[20];
int id;
double gpa;
};
Student students [] = { {"Jack",112,3.4},{"Mary",102,3.8},{"Mary",117,3.9}, {"Ala",333,3.5},{"Zero",101,4.0}};
struct StudentRule1 { //按姓名从小到大排
bool operator() (const Student & s1,const Student & s2) {
if( stricmp(s1.name,s2.name) < 0)
return true;
return false;
}
};
struct StudentRule2 { //按id从小到大排
bool operator() (const Student & s1,const Student & s2) {
return s1.id < s2.id;
}
};
struct StudentRule3 {//按gpa从高到低排
bool operator() (const Student & s1,const Student & s2) { return s1.gpa > s2.gpa;
}
};
void PrintStudents(Student s[],int size){
for(int i = 0;i < size;++i)
cout << "(" << s[i].name << "," << s[i].id <<"," << s[i].gpa << ") " ; cout << endl;
}
int main()
{
int n = sizeof(students) / sizeof(Student);
sort(students,students+n,StudentRule1()); //按姓名从小到大排
PrintStudents(students,n);
sort(students,students+n,StudentRule2()); //按id从小到大排
PrintStudents(students,n);
sort(students,students+n,StudentRule3()); //按gpa从高到低排
PrintStudents(students,n);
return 0;
}
结果:
(Ala,333,3.5) (Jack,112,3.4) (Mary,102,3.8) (Mary,117,3.9) (Zero,101,4)
(Zero,101,4) (Mary,102,3.8) (Jack,112,3.4) (Mary,117,3.9) (Ala,333,3.5)
(Zero,101,4) (Mary,117,3.9) (Mary,102,3.8) (Ala,333,3.5) (Jack,112,3.4)