插入对象作为键无法编译?

时间:2010-10-09 01:10:10

标签: c++ stl

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

#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 ::地图,   std :: allocator&gt; &GT; ::插入(物&安培)”   /usr/include/c++/4.4/bits/stl_map.h:499:   注意:候选人是:   的std ::对,   std :: _ Select1st&gt;,_ Compare,typename _Alloc :: rebind&gt; :: other&gt; :: iterator,bool&gt; std :: map&lt; _Key,_Tp,_Compare,   _Alloc&gt; :: insert(const std :: pair&amp;)[with _Key = Thing,_Tp = int,_Compare = std :: less,   _Alloc = std :: allocator&gt;]   /usr/include/c++/4.4/bits/stl_map.h:539:   注意:typename   std :: _ Rb_tree&lt; _Key,std :: pair,std :: _ Select1st&gt;,_ Compare,typename _Alloc :: rebind&gt; :: other&gt; :: iterator std :: map&lt; _Key,_Tp,_Compare,   _Alloc&gt; :: insert(typename std :: _ Rb_tree&lt; _Key,std :: pair,std :: _ Select1st&gt;,_Compare,typename _Alloc :: rebind&gt; :: other&gt; :: iterator,const std :: pair&amp;) [与   _Key = Thing,_Tp = int,_Compare = std :: less,_Alloc =   std :: allocator&gt;]

这是什么意思?我需要在Thing中定义另一个方法或运算符来进行编译吗?

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:3)

你不能单独插入一个键(Thing对象) - map::insert(至少在地图上)取一个​​std::pair<Thing,int>,以便插入由{{1}索引的值int }}。

然而 - 在我看来,你实际上想要使用Thing,因为你的Thing对象有自己的排序语义。重复封装的std::set<Thing>作为由int val键入的映射中的值是多余的,并且打破了您在此处的良好封装。

Thing

答案 2 :(得分:0)

std::map::insert希望您传递一个键值对。

mymap.insert(std::pair<Thing, int>(t2, 10));可行。

相关问题