例如:
struct node{
int val;
string key;
bool operator<(const node& other) const {
if (val != other.val) {
return val > other.val; // 距离小的优先
} else {
return key > other.key; // 距离相同,字母序小的优先(a < b,所以a>b为false,a先出队)
}
}
};
这段代码是在结构体(struct)内部定义的小于运算符重载(重载),主要用于指定该结构体对象之间的比较规则。下面详细解析:
1. 适用对象
这段代码是直接定义在struct node内部的,因此是针对该结构体本身的比较规则定义。当这个结构体用于需要比较的场景(如优先队列priority_queue)时,会自动使用这个规则。
它并非直接针对priority_queue,但priority_queue会依赖这种比较规则来确定元素的优先级。
2. 语法解析
这段代码的完整语法含义是:
// 在struct node内部定义
bool operator<(const node& other) const {
// 比较逻辑
if (val != other.val) {
return val > other.val; // 当val不同时,val小的对象"更小"
} else {
return key > other.key; // 当val相同时,key小的对象"更小"
}
}
operator<:重载了小于运算符,定义了两个node对象之间的"小于"关系const node& other:传入另一个node对象的常量引用(避免拷贝,保证不修改原对象)- 末尾的
const:表示这个成员函数不会修改当前对象的成员变量
3. 比较规则的实际效果
从代码逻辑来看,这个比较规则的实际效果是:
- 优先比较
val(注释中称为"距离"):val越小的对象,被判定为"更小" - 当
val相等时,比较key(注释中称为"字母"):key越小的对象,被判定为"更小"
这种规则在priority_queue中使用时,会让"更小"的元素优先级更高(因为priority_queue默认是最大堆,"小"的元素会被优先弹出)。
4. 与优先队列(pq)的关系
当把这个struct node作为priority_queue的元素类型时:
priority_queue<node> pq; // 会自动使用node中定义的operator<作为比较规则
priority_queue会根据operator<的返回值来维护堆结构,最终实现"距离小的优先,距离相同则字母序小的优先"的效果。
总结:这段代码是结构体内部的比较规则定义,而priority_queue只是使用该规则的场景之一。
浙公网安备 33010602011771号