通过重载 < 操作符
struct node
{
int math;
int chinese;
bool operator < (const node &a) const
{
return math<a.math;//math从小到大进行排序
}
};
自定义sort的cmp函数
对于一个结构体而言,有多个关键字,在使用sort的时候可以针对不同关键字进行排序
比如下面这个结构体node存储数学和语文成绩
struct node
{
int math;
int chinese;
}node[N];
仅仅以math为关键字进行排序
boo cmp(node a,node b)
{
return a.math<b.math;//按照数学成绩从小到大进行排序
}
sort(a,a+n,cmp);
优先以math为关键字排序,当math相等时,以Chinese为关键字排序
boo cmp(node a,node b)
{
if(a.math!=b.math) return a.math<b.math;
if(a.chinese!=b.chinese) return a.chinese<b.chinese;
}
sort(a,a+n,cmp);