我在编译时遇到了麻烦.我不明白编译器抛出的错误.一些代码来说明问题如下.
#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
}
Run Code Online (Sandbox Code Playgroud)
现在编译错误消息:
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中定义另一个方法或运算符来进行编译吗?
您需要mymap.insert(std::pair<Thing,int>(t1,x));
,x
您要映射到的值在哪里t1
.