哇,好久没来写博客了。
今天是发现了一个新大陆。
是这样的,我想随机生成一些整数对(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中存放结构体,也是同样的做法。