一. std::sort()函数
1. 默认方法
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
适用于自定义的vector数组,从小到大排序,比如:
vector<int> vec{20,34,1,34,14,7,9,40};
sort(vec.begin(),vec.end());
//或者
sort(vec.begin(), vec.begin() + 5);
2. 自定义比较函数
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
后面的comp就是自定义的比较函数
struct Compare{
bool operator()(const pair<int,int> &p1,const pair<int,int> &p2)
{
return p1.second < p2.second;
}
} comp_pair;
int main(int argc,char **argv)
{
std::vector<pair<int,int>> v;
srand((unsigned int)time(NULL));
for(int i = 0;i < 10;i++){
int r1 = rand() % 100;
int r2 = rand() % 150;
v.push_back({r1,r2});
}
for(auto it : v)
cout << it.first << " " << it.second <<", ";
cout << endl;
std::sort(v.begin(),v.end(),comp_pair);
for(auto it : v)
cout << it.first << " " << it.second <<", ";
cout << endl;
return 0;
}
也可以简单地定义一个bool函数
struct Coor
{
int x;
int y;
Coor(int x_ , int y_){ x = x_ ; y = y_ ; }
};
bool comp_coor(const Coor &c1,const Coor &c2){
return c1.y < c2.y;
}
int main(int argc,char **argv)
{
srand((unsigned int)time(NULL));
std::vector<Coor> coors;
for(int i = 0;i < 10;i++){
int r1 = rand() % 100;
int r2 = rand() % 150;
Coor coor(r1,r2);
coors.push_back(coor);
}
for(auto it : coors){
cout << it.x << " " << it.y << " , ";
}
cout << endl;
std::sort(coors.begin(),coors.end(),comp_coor);
for(auto it : coors){
cout << it.x << " " << it.y << " , ";
}
cout << endl;
return 0;
}