C++ map和set中的结构体

哇,好久没来写博客了。

今天是发现了一个新大陆。

是这样的,我想随机生成一些整数对(x,y),然后需要判断一个数对在之前有没生成过。直观的做法是弄一个bool型的二维数组,但是这样太耗费空间了,容易造成浪费。于是我想把每个整数对放在一个结构体里,然后将结构体作为map的key,将一个bool型作为map的value。这样建立一个映射的关系,来判断整数对是否出现过。


于是一开始我就这样写了:

struct numPair {
	int x;
	int y;

	numPair() {}
	numPair(int _x, int _y) :x(_x), y(_y) {}
};

可是当我想在map里插入这样一个结构体,就比如这样时,

map<numPair, bool> visit;
visit.insert(std::pair<numPair, bool>(numPair(10, 20),true));

VS编译器报了这样的错误:


============================================================================
错误 C2664 “void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert
(

std::initializer_list<std::pair<const _Kty,_Ty>>)”: 无法将参数 1 从“numPair”转换为“std::pair<const _Kty,_Ty> &&”

============================================================================


这就是问题所在!map中的元素是按照key的大小进行排序的。所以需要在自定义结构题中加入比较大小函数。于是我进行了修改,重载了<运算符:


struct numPair {
	int x;
	int y;

	numPair() {}
	numPair(int _x, int _y) :x(_x), y(_y) {}

	bool operator<(const numPair& other) {
		return x < other.x || x == other.x && y < other.y;
	}
};

结果依然报同样的错误

============================================================================

错误 C2664“void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(

std::initializer_list<std::pair<const _Kty,_Ty>>)”: 无法将参数 1 从“numPair”转换为“std::pair<const _Kty,_Ty> &&”

============================================================================


想了半天,最后在stackoverflow中找到了问题所在:<的重载函数需要加上const !!!!!

struct numPair {
	int x;
	int y;

	numPair() {}
	numPair(int _x, int _y) :x(_x), y(_y) {}

	bool operator<(const numPair& other) const {
		return x < other.x || x == other.x && y < other.y;
	}
};



如果想在set中存放结构体,也是同样的做法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值