【发布时间】:2012-11-20 18:59:17
【问题描述】:
试图复习我的 C++ 和 STL 熟练程度,遇到了一个问题,我定义的结构为键控的 std::map。相关代码:
typedef struct key_t {
int a;
int b;
bool operator==(const key_t& rhs)
{
return (a == rhs.a) && (b == rhs.b);
}
bool operator<(const key_t& rhs) //added the when I saw this error, didn't help
{
return a < rhs.a;
}
} key_t;
std::map<key_t, int> fooMap;
void func(void)
{
key_t key;
key.a = 1;
key.b = 2;
fooMap.insert(std::pair<key_t, int>(key, 100));
}
错误如下:
"/opt/[redacted]/include/functional", line 133: error: no operator "<" matches these operands
operand types are: const key_t < const key_t
detected during:
instantiation of "bool std::less<_Ty>::operator()(const _Ty &, const _Ty &) const [with _Ty=key_t]" at line 547 of "/opt/[redacted]/include/xtree"
instantiation of "std::_Tree<_Traits>::_Pairib std::_Tree<_Traits>::insert(const std::_Tree<_Traits>::value_type &) [with _Traits=std::_Tmap_traits<key_t, UI32, std::less<key_t>, std::allocator<std::pair<const key_t, UI32>>, false>]"
我做错了什么?将结构用作地图键是否完全糟糕/不可能?还是我忽略了其他什么?
【问题讨论】:
-
+1 对于格式正确的代码,清楚地解释了问题并显示了具体错误。
-
您的
operator<和您的operator==不一致,因为只有operator==测试b。这不是您的问题的原因,但除非您解决它,否则您是在自找麻烦。可能您应该将operator<更改为return a < rhs.a || a == rhs.a && b < rhs.b;