and how can I do it in C++?
+8
A:
You can use any type as a map key, as long as it implements an operator<
(plus the usual copy-and-assign requirements for values stored in containers).
For instance:
struct example { int x; }
bool operator < (const example &l, const example &r) { return l.x < r.x; }
std::map<example, int> values;
Alternatively, you may provide a comparison function as the third argument of the map template instead of defining operator<
. More details here (parameter Compare
).
Victor Nicollet
2010-10-14 17:13:08
"as long as it implements an operator<" - or there's a specialization of `std::less` for the type. `map` uses `less` by default, and `less` uses `operator<` by default, so there are two routes in.
Steve Jessop
2010-10-14 17:42:54