STL (standard template library)标准模板库
使用时需要
#include<algorithm>
使用STL中 sort() 进行排序
用法一 从小到大排序
实例如下:
用法二 从大到小排序
用法三 自定义排序
代码实例1
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Rule1{
bool operator()(const int & a1,const int & a2){
return a1 > a2;//若a1>a2 则a1应该排在a2的前面 即从大到小
}
};
struct Rule2{
bool operator()(const int & a1,const int & a2){
return a1%10 < a2%10;//若a1%10 < a2%10 则a1应该排在a2的前面 即按照个位数从小到大
}
};
void Print(int a[],int size){
for(int i=0;i < size;i++) cout << a[i]<<",";
cout << endl;
}
int main(){
int a[] = {12,24,3,65,43};
sort(a,a+sizeof(a)/sizeof(int));
cout << "1) ";
Print(a,sizeof(a)/sizeof(int));
sort(a,a+sizeof(a)/sizeof(int),Rule1());
cout << "2)";
Print(a,sizeof(a)/sizeof(int));
sort(a,a+sizeof(a)/sizeof(int),Rule2());
cout << "3)";
Print(a,sizeof(a)/sizeof(int));
return 0;
}
代码实例2
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Student {
char name[20];
int id;
double gpa;
};
Student stu [] = {
{"Jack",112,3.4},{"Mary",102,3.8},{"Mary",117,3.9},{"Ala",222,3.5},{"Zero",101,4.0}
};
//struct stuRole1{
// bool operator()(const int & a1,const int & a2){
//
// 若a1应该在a2前面,则返回true。
// 否则返回false
// }
//};
struct stuRole1{//按姓名从小到大
bool operator()(const Student & s1,const Student & s2){
if( stricmp( s1.name,s2.name) < 0)
return true;
return false;
}
};
struct stuRole2{//按id从小到大排序
bool operator()(const Student & s1,const Student & s2){
return s1.id < s2.id;
}
};
struct stuRole3{//按gpa从高到低排序
bool operator()(const Student & s1,const Student & s2){
return s1.gpa > s2.gpa;
}
};
void PrintStu(Student stu[],int n){
for(n--;n>=0;n--){
cout<<"(";
cout << stu[n].name<<","<<stu[n].id<<","<<stu[n].gpa;
cout <<")";
}
cout<<endl;
}
int main(){
int n = sizeof(stu)/sizeof(Student);
sort(stu,stu+n,stuRole1());
PrintStu(stu,n);
sort(stu,stu+n,stuRole2());
PrintStu(stu,n);
sort(stu,stu+n,stuRole3());
PrintStu(stu,n);
return 0;
}
注意:sort函数的时间复杂度为O(log(n))