作用
帮助优先队列、sort函数等对结构体进行排序时进行自定义变量比较
方式
①重载函数可以写在结构体里
模板
<函数类型> operator <运算符> (<参数表(一个参数即可)>) const
{
<函数体>
}
eg
struct point{ //链式前向星模拟邻接表
int to; //终点
int w; //权重
int next; //上个同起的边的位置
bool operator < (const point &b) const{
return w > b.w;// 最小堆反过来
}
};
②单独写个函数,不用放在结构体里
模板
<函数类型> operator <运算符> (<参数表(两个参数)>)
{
<函数体>
}
//加引用是直接对原对象进行操作,不用像按值传递一样要把对象赋值过来
bool operator < (point &a,point &b){
if(a.to == b.to)
return a.w > b.w;// 最小堆反过来
return a.w < b.w;
}