1. sort函数的使用
1.1 sort函数的一般使用
头文件:
#include <algorithm>
#include<iostream>
#include<algorithm>//加头文件
using namespace std;
//按照从大到小进行排序
bool cmp(const int &a,const int &b){
return a>b;
}
int main(){
int num[]={3,0,12,6,9,10,-5,8,7,22};
//sort(num,num+10);
//前五个数从小到大排序
sort(num,num+5);//sort(开始位置,结束位置);默认从小到大排序
//后五个数从大到小排序
sort(num+5,num+10,cmp);
for(int i = 0;i<10;i++){
cout<<num[i]<<" ";
}
cout<<endl;
return 0;
}
1.2 sort函数和结构体的组合
1.2.1 方法1:自定义比较函数
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int x,y;
};
bool cmp_node(const node &a,const node &b){
if(a.x == b.x){//如果x相同,按照y的值从大到小排序
return a.y>b.y;
}
return a.x>b.x;//优先按照x的值从大到小排序
}
int main(){
node t[10];
t[0].x = 5,t[0].y = 1;
t[1].x = 7,t[1].y = 0;
t[2].x = 6,t[2].y = 9;
t[3].x = 6,t[3].y = 22;
t[4].x = 6,t[4].y = 15;
sort(t,t+5,cmp_node);
for(int i = 0;i<5;i++){
cout<<t[i].x<<" "<<t[i].y<<endl;
}
return 0;
}
1.2.2 方法2:重载 <(小于)符号
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int x,y;
//重载操作符<
bool operator< (const node &b) const{
if(this->x == b.x)//如果x相同,按照y的值从大到小排序
return this->y>b.y;
return this->x>b.x;//优先按照x的值从大到小排序
}
};
int main(){
node t[10];
t[0].x = 5,t[0].y = 1;
t[1].x = 7,t[1].y = 0;
t[2].x = 6,t[2].y = 9;
t[3].x = 6,t[3].y = 22;
t[4].x = 6,t[4].y = 15;
sort(t,t+5);//写法不变
for(int i = 0;i<5;i++){
cout<<t[i].x<<" "<<t[i].y<<endl;
}
return 0;
}
总结:自定义比较函数时,切记不要使用>=或<=。