4

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

我究竟做错了什么?将结构用作地图键是否完全糟糕/不可能?还是我忽略的其他东西?

4

2 回答 2

5

这个

 bool operator<(const key_t& rhs)

需要是一个 const 方法

 bool operator<(const key_t& rhs) const

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

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

于 2012-11-20T19:00:55.243 回答
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 )有效地相等。

于 2012-11-20T19:02:36.443 回答