【问题标题】:Insert with object as key fails to compile?以对象为键插入无法编译?
【发布时间】:2011-04-23 03:45:26
【问题描述】:

我无法编译一些东西。我不明白抛出的错误 由编译器。下面是一些说明问题的代码。

#include <map>

using namespace std;

class Thing
{
public:
    Thing(int n):val(n) {}

    bool operator < (const Thing& rhs) const
    {
        return val < rhs.val;
    }

    int getVal() { return val; }

private:
    int val;
};


int main(int argc, char* argv[])
{
    std::map<Thing, int> mymap;
    Thing t1(1);
    Thing t2(10);
    Thing t3(5);

    mymap[t1] = 1; // OK

    mymap.insert(t1); // Compile error
}

现在编译器错误信息:

test.cpp: 在函数'int main(int, char**)’: test.cpp:34: 错误: 否 调用的匹配函数 'std::map, std::allocator > >::insert(Thing&)’ /usr/include/c++/4.4/bits/stl_map.h:499: 注:候选人是: 标准::对, std::_Select1st >, _Compare, typename _Alloc::rebind >::other>::iterator, bool> std::map<_key _tp _compare _alloc>::insert(const std::pair&) [with _Key = Thing, _Tp = int, _Compare = std::less, _Alloc = std::allocator >] /usr/include/c++/4.4/bits/stl_map.h:539: 注意:类型名称 std::_Rb_tree<_key std::pair std::_select1st>, _Compare, typename _Alloc::rebind >::other>::iterator std::map<_key _tp _compare _alloc>::insert(typename std::_Rb_tree<_key std::pair std::_select1st>, _Compare, typename _Alloc::rebind >::other>::iterator, const std::pair&) [with _Key = 事物,_Tp = int,_Compare = std::less,_Alloc = std::allocator >]

这是什么意思?我需要在 Thing 中定义其他方法或运算符以使其编译吗?

【问题讨论】:

  • getVal() 方法也可能是 const-qualified。
  • @ArunSaha - 谢谢,这只是一个例子。

标签: c++ stl


【解决方案1】:

您需要mymap.insert(std::pair&lt;Thing,int&gt;(t1,x));,其中x 是您要映射到t1 的值。

【讨论】:

  • 是的。或mymap.insert(std::make_pair(t1,x)); 或mymap.insert(std::map&lt;Thing,int&gt;::value_type(t1,x))。如果你有一个typedef 代表std::map&lt;Thing,int&gt;,那么最后一个会更有用。
【解决方案2】:

您不能单独插入键(Thing 对象) - map::insert(至少在您的地图上)采用 std::pair&lt;Thing,int&gt; 以便插入由键 Thing 索引的值 int。

但是 - 在我看来,您实际上想要使用 std::set&lt;Thing&gt;,因为您的 Thing 对象有自己的排序语义。重复封装的 int val 作为由 Thing 键入的映射中的值是多余的,并且会破坏您在此处的良好封装。

int main(int argc, char* argv[])
{
    std::set<Thing> myset;
    Thing t1(1);
    Thing t2(10);
    Thing t3(5);

    std::pair<std::set<Thing>::iterator, bool> result = myset.insert(t1);

    std::set<Thing>::iterator iter = myset.find(t1);
}

【讨论】:

    【解决方案3】:

    std::map::insert 期望你传递一个键值对。

    mymap.insert(std::pair&lt;Thing, int&gt;(t2, 10)); 可以工作。

    【讨论】:

      猜你喜欢
      • 2015-06-06
      • 2015-05-08
      • 1970-01-01
      • 2021-08-13
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多