0
点赞
收藏
分享

微信扫一扫

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

水沐由之 2022-02-25 阅读 52

知识点

  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

举报

相关推荐

0 条评论