std :: map insert error:没有运算符"<"匹配这些操作数

lau*_*ote 4 c++ stdmap operators

试图提高我的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));
}
Run Code Online (Sandbox Code Playgroud)

错误看起来像这样:

"/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>]"
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?使用结构作为地图键是不是很糟糕/不可能?或者其他我忽略的东西?

Dou*_* T. 5

这个

 bool operator<(const key_t& rhs)
Run Code Online (Sandbox Code Playgroud)

需要是一个const方法

 bool operator<(const key_t& rhs) const
Run Code Online (Sandbox Code Playgroud)

这两个是不同的签名,并std::less寻找后者.后者作为const方法,暗示它不会修改对象.然而,没有const的前者可能意味着this可以执行修改.

一般来说,拥有const方法是个好主意,即使你可以抛弃它,也意味着客户承诺不会进行任何修改.