关于struct自定义类型的set/priority_queue重载<运算符

知识点

  1. 运算符重载
  2. 成员函数
  3. 友元函数
  4. 一般函数
  5. const

使用struct自定义类型(比如自定义node)是我做题中经常使用的方法,对自定义类型使用set或者priority_queue也是我喜欢干的事,但是我在做题的过程中就发现了一些问题。

#include <set>
using namespace std;

就像下面一样我照常写了一个node结构体:

struct node{
	int x ,y;
	bool operator < (const nodeU& b){
		return x < b.x;
	}
};

当我写出主函数,却无法编译,报出一长串的编译错误。

int main(){
	set<node> st;
	st.insert({1, 2});
	return 0;
}

先直接说原因:
因为在set的insert函数是这样的:
pair<iterator,bool> insert (const value_type& val);
注意到类型val前有一个const 修饰,但是在c++中const修饰的对象,只能调用它有const修饰的成员函数,而如果<重载不加const,就违反了这一规则,所以会报错。

拓展

注意到下面这两种结构体写法能编译成功:

struct node{
	int x, y;
	bool operator < (const node& b)const{
		return x < b.x;
	}
};
struct node{
	int x, y;
	friend bool operator < (const node& a, const node& b){
		return a.x < b.x;
	}
};
struct node{
	int x, y;
};
bool operator < (const node& a, const node& b){
	return a.x < b.x;
}

可以得到友元函数与一般函数是不受这条规则制约的,所以可以像上面那样写而不会报错。

参考文献:https://blog.csdn.net/GMstart/article/details/7046140?utm_source=app&app_version=5.0.1&code=app_1562916241&uLinkId=usr1mkqgl919blen
鸣谢:zcx

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值