Unordered associative containers (C++): Difference between revisions

Content deleted Content added
dmy template
No edit summary
Line 202:
}
</source>
 
==Custom hash functions==
In order to use custom objects in std::unordered_map, a custom hash functor must be defined. This function takes a const reference to the custom type and returns a size_t
<code>
struct X{int i,j,k;};
 
struct hash_X{
size_t operator()(const X &x){
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
}
};
</code>
 
The user defined function can be used as is in std::unordered_map, by passing it as a template parameter
<code> std::unordered_map<X,int,hash_X> my_map;</code>
 
Or can be set as the default hash function by specializing the std::hash function
<code>
namespace std {
template <>
class hash<X>{
public :
size_t operator()(const X &x ) const{
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
}
};
};
 
//...
std::unordered_map<X,int> my_map;
</code>
 
 
==References==