std::map is a templated class. The key has to match a certain concept called strict weak ordering which guarantees:
- Keys are less-than-comparable (overload operator< or give the map a custom comparator)
- If element A is less than B, B can't be less than A
- If element A is less than B and B is less than C, then A is less than C
Here's an example with a custom type as key:
#include <map>
#include <iostream>
struct Custom{ Custom(int c): c(c){} int c; };
bool operator< (Custom const &a, Custom const &b){ return a.c< b.c; }
int main(){ std::map<Custom, int> m; m[Custom(42)]= 42; std::cout<< m[Custom(42)]; }
That said, std::map is not the exact equivalent of Java's hash map. C++11 has std::unordered_map
for that. With unordered_map
, you can define your own std::hash template for your own type to persist your custom type as hash keys.