栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

关于struct自定义类型的set/priority

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于struct自定义类型的set/priority

知识点
    运算符重载成员函数友元函数一般函数const

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

#include 
using namespace std;

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

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

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

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

先直接说原因:
因为在set的insert函数是这样的:
pair 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/743679.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号