试图提高我的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>]"
我做错了什么?使用结构作为地图键是不是很糟糕/不可能?或者其他我忽略的东西?
答案 0 :(得分:5)
此
bool operator<(const key_t& rhs)
需要是一个const方法
bool operator<(const key_t& rhs) const
这两个是不同的签名,std::less
寻找后者。后者作为const方法,暗示它不会修改对象。然而,前者没有const可能意味着可以执行对this
的修改。
一般来说,拥有const
方法是一个好主意,即使你可以抛弃它,也意味着客户承诺不会进行任何修改。
答案 1 :(得分:1)
首先,运营商必须是const
。 (而且您不需要==
运算符。)
你在哪里学习使用typedef作为struct
。没有理由。
最后,如果你想要两个元素作为参与的一部分参与 关键,你必须比较它们:
struct Key
{
int a;
int b;
bool operator<( Key const& rhs ) const
{
return a < rhs.a
|| ( !(rhs.a < a) && b < rhs.b );
}
};
否则,Key( 1, 2 )
和Key( 1, 3 )
将会有效
相等。