C++ 结构体 运算符重载 const使用问题

问题

在刷题的时候经常会遇到需要自己写结构体并且自己重载比较函数的情况,特别是有时候需要用一些STL容器(如priority_queue)储存结构体的时候。在重载比较函数的时候有些疑惑于哪里需要加const,所以今天总结一下。
看下面的简单例子:

struct Student{
    int ID;
    bool operator<(const Student &student) {
        return ID < student.ID;
    }
    Student(int id): ID(id){}
};

int main() {
    cout << (Student(111) < Student(222)) << endl;
    return 0;
}

输出结果是1也就是true。但是当我们更改main函数时:

int main() {
    priority_queue<Student> q;
    q.push(Student(111));
    return 0;
}

此时会报错:
在这里插入图片描述
当我们更改运算符重载函数为如下后可以顺利运行

struct Student{
    int ID;
    bool operator<(const Student &student) const{
        return ID < student.ID;
    }
    Student(int id): ID(id){}
};
int main() {
    priority_queue<Student> q;
    q.push(Student(111));
    return 0;
}

可以看出,当我们将重载函数改为const函数时即可顺利运行。分析报错信息以及简单查询STL底层代码可以看出,当priority_queue在调用我们所写的重载比较函数时,输入的参数为const的student对象。只有const成员函数才能访问const对象中的数据,而非const成员函数不能。所以才会出现上述错误。

总结

在使用STL容器如priority_queue等储存结构体时,如果需要重载比较函数且STL容器需要调用该比较函数时,要将比较函数写为const函数。即如下写法:bool operator<(const T &t) const {}

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值