用sort 排序 struct
+++
//method 1
struct node{
int k,s;
}p[5005];
bool cmp1(node x,node y){
return x.s>y.s; //定义降序排序(从大到小)
}
bool cmp2(node x,node y){
return x.k<y.k; //定义升序排序(从小到大)
}sort(p+1,p+n+1,cmp2); //排序
eg:
#include<iostream>
#include<algorithm>
using namespace std;
struct b {
int k, s;
};
bool compare(b x, b y)
{
if (x.k != y.k) return x.k > y.k;
return x.s > y.s;//降序排序
}
int main()
{
b p[5] = { {2, 4}, {2, 8}, {5, 9}, {1, 4}, {2, 5} };
sort(p, p + 5, compare);//point
for (auto x : p)
cout << x.k << " " << x.s << endl;
system("pause");
return 0;
}
//method 2
struct b {
int k, s;
bool operator< (const b & t)const//实现降序排序
{
if (k != t.k) return k < t.k;
return s < t.s;
}
};
eg:
#include<iostream>
#include<algorithm>
using namespace std;
struct b {
int k, s;
bool operator< (const b & t)const
{
if (k != t.k) return k < t.k;
return s < t.s;
}
};
int main()
{
b p[5] = { {2, 4}, {2, 8}, {5, 9}, {1, 4}, {2, 5} };
sort(p, p + 5);//参数只需要两个迭代器,不需要第三个参数
for (auto x : p)
cout << x.k << " " << x.s << endl;
system("pause");
return 0;
}