我在编译时遇到了麻烦 . 我不明白编译器抛出的错误 . 下面是一些用于说明问题的代码 .
#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 回答
你不能单独插入一个键(Thing对象) -
map::insert
(至少在你的 Map 上)取一个std::pair<Thing,int>
,这样你就可以插入int
索引的int
.但是 - 在我看来,你实际上想要使用
std::set<Thing>
,因为你的Thing对象有自己的排序语义 . 重复封装的int val
作为Thing
键入的映射中的值是多余的,并打破了您在此处的良好封装 .您需要
mymap.insert(std::pair<Thing,int>(t1,x));
,其中x
是您要映射到t1
的值 .std::map::insert
希望你传递一个键值对 .mymap.insert(std::pair<Thing, int>(t2, 10));
会奏效 .