结构体的优先级设置
- 此函数将数值小的设置为优先级高,可以这样理解:重载的为小于号<,所以假设传进的是数字的大小按照小的在前面传进来的,而返回值则为设置的优先级的大小,return f1.price>f2.price; 则代表f1.price 的优先级大于f2.price 的优先级
struct fruit{
string name;
int price;
friend bool operator < (fruit f1,fruit f2){
return f1.price>f2.price;
}
};
- 重载时只能用小于号<,用大于号会报错,因为从数学上来说只需要重载小于号,即f1>f2等价于判断f2<f1,而f1==f2则等价于判断!(f1<f2)&&!(f2>f1)
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct fruit{
string name;
int price;
friend bool operator < (fruit f1,fruit f2){
return f1.price>f2.price;
}
}f1,f2,f3;
int main()
{
priority_queue<fruit> q;
f1.name="桃子";
f1.price=3;
f2.name="梨子";
f2.price=4;
q.push(f1);
q.push(f2);
cout<<q.top().name<<" "<<q.top().price<<endl;
return 0;
}