【问题标题】:std::map insert error: no operator "<" matches these operandsstd::map 插入错误:没有运算符“<”匹配这些操作数
【发布时间】: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&lt; 和您的operator== 不一致,因为只有operator== 测试b。这不是您的问题的原因,但除非您解决它,否则您是在自找麻烦。可能您应该将operator&lt; 更改为return a &lt; rhs.a || a == rhs.a &amp;&amp; b &lt; rhs.b;

标签: c++ operators stdmap


【解决方案1】:

这个

 bool operator<(const key_t& rhs)

需要是一个 const 方法

 bool operator<(const key_t& rhs) const

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

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

【讨论】:

  • 谢谢。我来自 C 环境,所以我不熟悉 const 应用于方法的用法。
【解决方案2】:

首先,操作员必须是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 ) 将有效地 相等。

【讨论】:

  • 不需要它,但看到 C 风格的结构定义并不少见。
  • @DougT。我希望看到它的唯一地方是设计用于 C(以及 C++)的标头中。我不能说我曾经在专业编写的 C++ 代码中见过它。这通常表明作者不懂 C++,并且您不想雇用他。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 2013-04-09
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多