std::map 插入错误:没有运算符"<"与这些操作数匹配

std::map insert error: no operator "<" matches these operands

本文关键字:操作数 lt 错误 插入 std 运算符 map      更新时间:2023-10-16

试图复习我的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>]"

我做错了什么?使用结构作为地图键只是非常糟糕/不可能吗?还是我忽略了什么?

 bool operator<(const key_t& rhs)

需要是一个常量方法

 bool operator<(const key_t& rhs) const

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

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

对于初学者来说,运算符必须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 )将有效地平等。