Insert with object as key fails to compile?
我找不到要编译的东西。我不明白被排除的错误由编译器编写。下面是一些说明问题的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #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: In function ‘int main(int,
char**)’: test.cpp:34: error: no
matching function for call to
‘std::map,
std::allocator > >::insert(Thing&)’
/usr/include/c++/4.4/bits/stl_map.h:499:
note: candidates are:
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:
note: 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中定义另一个方法或运算符来编译它吗?
您需要
不能单独插入键(物对象)-
然而,在我看来,您实际上想要使用
1 2 3 4 5 6 7 8 9 10 11 | 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); } |
江户十一〔11〕行。