struct类型排序
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
int a;
int b;
};
bool com(const Date x,const Date y)
{
if(x.a==y.a)
return x.b>y.b;
return x.a>y.a;
}
int main()
{
Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
sort(dat,dat+5,com); //按照第1个数由大到小排序,当第1个数相同时,按照第2个数由大到小排序
for(int i=0;i<5;i++)
{
cout<<dat[i].a<<" "<<dat[i].b<<endl;
}
return 0;
}
输出:
5 6
3 8
3 7
2 9
1 10
bool operator
型写法
operator重载小于运算符,可以设定由小到大排序,也可以设定由大到小排序
两种写法,可以写在struct内,也可以写在struct外。
这种写法区分于那种重载()运算符写法。
在struct外重载小于运算符
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
int a;
int b;
};
bool operator<(const Date &x,const Date &y)
{
if(x.a == y.a)
return x.b>y.b;
return x.a>y.a;
}
int main()
{
Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
sort(dat,dat+5);
for(int i=0;i<5;i++)
{
cout<<dat[i].a<<" "<<dat[i].b<<endl;
}
return 0;
}
输出:
5 6
3 8
3 7
2 9
1 10
在struct内重载小于运算符
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
int a;
int b;
bool operator < (const Date &y) const
{
return b>y.b; //设定按照b由大到小排列
}
};
int main()
{
Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
sort(dat,dat+5);
for(int i=0;i<5;i++)
{
cout<<dat[i].a<<" "<<dat[i].b<<endl;
}
return 0;
}
输出:
1 10
2 9
3 8
3 7
5 6