原型:
void sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
_Compare __comp)
- __first:排序区间的起始地址
- __last:排序区间的末尾地址
- __comp:排序方法
以上排序区间依然是左闭右开
两个参数时,默认升序
vector<int> v = {3,1,4,6,0,9};
sort(v.begin(), v.end());//升序
int a[6] = {3,1,4,6,0,9};
sort(a, a+6);//升序
自定义排序方法
1、升序
bool cmp(const int a, const int b){
return a < b;
}
int main(){
vector<int> v = {3,1,4,6,0,9};
sort(v.begin(), v.end(), cmp);
return 0;
}
2、降序
bool cmp(const int a, const int b){
return a > b;
}
int main(){
vector<int> v = {3,1,4,6,0,9};
sort(v.begin(), v.end(), cmp);
return 0;
}
若排序的数据类型支持“<”、“>”等比较运算符,则可以使用STL中提供的函数
- 升序:sort(begin, end, less < data-type >());
- 降序:sort(begin, end, greater< data-type >());
上述的begin,end表示地址,不是索引
<int> v = {3,1,4,6,0,9};
sort(v.begin(), v.end(), less<int>());//升序
sort(v.begin(), v.end(), greater<int>());//降序
结构体排序
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Person{
float height;
float weight;
Person(float h, float w){
height = h;
weight = w;
}
};
//身高不同按照身高降序,身高相同按照体重降序
bool cmp(Person p1, Person p2){
if(p1.height != p2.height){
return p1.height > p2.height;
}else{
return p1.weight > p2.weight;
}
}
int main(){
vector<Person> persons = {Person(160, 100), Person(170, 130), Person(170, 120), Person(180, 100)};
sort(persons.begin(), persons.end(), cmp);
for(auto p : persons){
cout<<p.height<<" "<<p.weight<<endl;
}
return 0;
}