C++定义:
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
参数解释:
- 第一个参数first:是要排序的起始地址 [ 包含 ]
- 第二个参数last:是结束的地址 [ 不包含 ]
- 最后一个数据的后面一个的地址
第三个参数comp是排序准则:可以是从升序也可是降序
vector 中
vector<int>V;
V.push_back(-1);
V.push_back(12);
V.push_back(8);
sort (num.begin(),num.end());//从小到大排序
数组中
int a[]={45,12,34,77,90,11,2,4,5,55};
sort(a,a+10);
元素自身包含了比较关系,如int,double等基础类型
- 可以直接进行比较greater
()** **递减, less() ** 递增**int s[]={34,56,11,23,45};
vector<int>arr(s,s+5);//拷贝数组s的数据
sort(arr.begin(),arr.end(),greater<int>());//递减
sort(arr.begin(),arr.end(),less<int>()); //递增
2.自定义cmp准则 [ 5种方式 ]
作用**
按照自己想要的方式来排序1.在vector中按照自定义准则排序
# include<iostream>
# include<algorithm>
# include<vector>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(void){
int a[]={45,12,34,77,90,11,2,4,5,55};
sort(a,a+10,cmp);//自定义排序准则
system("pause");
return 0;
}
2. 元素本身为class或者struct
写在类内 ( 依靠重载 )
两种方式:
- 可以直接进行比较greater
sort(vec.begin(), vec.end());
- 备注:类内重载 <
sort(vec.begin(), vec.end(),Node());
备注:类内重写仿函数( **重载()**)
struct Node{
int x, y;
Node(int x,int y):x(x),y(y){}
// 1.重载"<"运算符(写在类内部)
bool operator<(const Node& a)const { // 返回true,表示this的优先级小于a
// x大的排在前面;x相同时,y大的排在前面
if (x_ == a.x_) return y_ > a.y_;
return x_ > a.x_;
}
// 2.重写仿函数(写在类内部)
bool operator()(Node& a, Node& b) const { // 返回true,表示this的优先级小于a
// x大的排在前面;x相同时,y大的排在前面
if (a.get_x() == b.get_x()) return a.get_y() > b.get_y();
return a.get_x() > b.get_x();
}
};
写在类外
两种方式:
sort(vec.begin(), vec.end());
- 备注:类外重载 <
bool operator<(Node& a, Node& b) { // 返回true,表示this的优先级小于a
// x大的排在前面;x相同时,y大的排在前面
if (a.get_x() == b.get_x()) return a.get_y() > b.get_y();
return a.get_x() > b.get_x();
}
- 备注:类外重载 <
sort(vec.begin(), vec.end(), cmp) ;
- 备注:类外重写仿函数类( **重载()**)
注意**
cmp返回值bool类型**
//仿函数类
struct cmp{
bool operator()(node a, node b){
if (a.x == b.x) return a.y >= b.y;
else return a.x > b.x;
}
};