首页 文章

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

提问于
浏览
2

我在编译时遇到了麻烦 . 我不明白编译器抛出的错误 . 下面是一些用于说明问题的代码 .

#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 :: pair,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:注意:typename 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 = Thing,_Tp = int,_Compare = std :: less,_Alloc = std :: allocator>]

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

3 回答

  • 9

    你不能单独插入一个键(Thing对象) - map::insert (至少在你的 Map 上)取一个 std::pair<Thing,int> ,这样你就可以插入 int 索引的 int .

    但是 - 在我看来,你实际上想要使用 std::set<Thing> ,因为你的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

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

  • 0

    std::map::insert 希望你传递一个键值对 .

    mymap.insert(std::pair<Thing, int>(t2, 10)); 会奏效 .

相关问题