c++ - std::maps with user-defined types as key -
i'm wondering why can't use stl maps user-defined classes. when compile code below, cryptic error message. mean? also, why happening user-defined types? (primitive types okay when used key)
c:\mingw\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h||in member function `bool std::less<_tp>::operator()(const _tp&, const _tp&) const [with _tp = class1]':|
c:\mingw\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_map.h|338|instantiated `_tp& std::map<_key, _tp, _compare, _alloc>::operator[](const _key&) [with _key = class1, _tp = int, _compare = std::less, _alloc = std::allocator >]'|
c:\users\admin\documents\dev\sandbox\sandbox\sandbox.cpp|24|instantiated here|
c:\mingw\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h|227|error: no match 'operator<' in '__x < __y'| ||=== build finished: 1 errors, 0 warnings ===|
#include <iostream> #include <map> using namespace std; class class1 { public: class1(int id); private: int id; }; class1::class1(int id): id(id) {} int main() { class1 c1(1); map< class1 , int> c2int; c2int[c1] = 12; return 0; }
you don't have define operator<
class, actually. can make comparator function object class it, , use specialize std::map
. extend example:
struct class1compare { bool operator() (const class1& lhs, const class1& rhs) const { return lhs.id < rhs.id; } }; std::map<class1, int, class1compare> c2int;
it happens default third template parameter of std::map
std::less
, delegate operator<
defined class (and fail if there none). want objects usable map keys, not have meaningful comparison semantics, , don't want confuse people providing operator<
on class that. if that's case, can use above trick.
yet way achieve same specialize std::less
:
namespace std { template<> struct less<class1> { bool operator() (const class1& lhs, const class1& rhs) const { return lhs.id < rhs.id; } }; }
the advantage of picked std::map
"by default", , yet not expose operator<
client code otherwise.
Comments
Post a Comment