结构体排序的两种实现方法
1.使用sort函数,重写排序规则。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
int x;
int y;
}a[10];
bool cmp(node a, node b)
{
return a.x > b.x; //从大到小排列
// return a.x < b.x; 从小到大排列
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i ++)
cin >> a[i].x >> a[i].y;
sort(a,a+n,cmp);
for(int i = 0; i < n; i ++)
cout << a[i].x << ' ' << a[i].y << endl;
return 0;
}
结果演示
2.在结构体中自定义排序,重小于号
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
int x;
int y;
bool operator<(const node &a) const{
return x < a.x; //从大到小排序
// x > a.x; //从小到大排序
}
//这里的排序是根据每个结构体内部的x进行排序
}a[10];
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i ++)
cin >> a[i].x >> a[i].y;
sort(a,a+n);
for(int i = 0; i < n; i ++)
cout << a[i].x << ' ' << a[i].y << endl;
return 0;
}
其实这两种排序都差不多,我推荐大家两种都要学会。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main(){
priority_queue<int> q;//默认是大根堆
q.push(1);
q.push(2);
q.push(3);
cout << q.top() << endl;
//元素类型、存储元素的容器、排序方式
//如果是int,char,string,double,long long 等,可以直接使用
//如果是结构体,自定义cmp,或者内部实现结构体重载
//
priority_queue<int,vector<int>,less<int> > q2;
q2.push(2);
q2.push(3);
q2.push(4);
cout << q2.top() << endl;
return 0;
}
/* 内部实现是一个堆
q.push(1);加入一个数
q.pop();弹出一个数
q.top()最大或最小的一个数
q.size()长度
*/
上面所描述的是默认的变量类型。然而对于自定义的结构体类型需要采用另外一种方法。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
int x;
int y;
friend operator <(node a, node b) //第一种自定义排序
{
return a.x < b.x; //从大到小开始排序,因为内部实现是堆,相当于两个孩子比根小
}
};
int main(){
priority_queue<node> q;
q.push({1,2});
q.push({2,3});
q.push({3,4});
cout << q.top().x << ' ' << q.top().y << endl;
}
如果想要和sort(a,a+1,cmp)这样的话,这样一种方法
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
int x;
int y;
};
struct cmp{
//通常这里尽量加const和&这两个,当数据量比较庞大时,提高效率
bool operator () (const node &a, const node &b)
{
return a.x < b.x; //从大到小排序
}
};
int main(){
//我个人认为这里是和sort(a,a+1,cmp)类似,
priority_queue<node,vector<node>, cmp> q;
q.push({1,2});
q.push({2,3});
q.push({3,5});
cout << q.top().x << ' ' << q.top().y << endl;
//输出结果是3 5
}