Unordered associative containers (C++)
In the programming language C++, unordered associative containers are a group of class templates in the C++ Standard Library that implement hash table variants. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. The following containers are defined in the current revision of the C++ standard: The unordered associative containers are similar to the associative containers in the C++ Standard Library but have different constraints. As their name implies, the elements in the unordered associative containers are not ordered. This is due to the use of hashing to store objects. The containers can still be iterated through like a regular associative container. HistoryThe first widely used implementation of hash tables in the C++ language was The Overview of functionsThe containers are defined in headers named after the names of the containers, e.g.,
Usage example#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, int> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
std::cout << "september -> " << months["september"] << std::endl;
std::cout << "april -> " << months["april"] << std::endl;
std::cout << "december -> " << months["december"] << std::endl;
std::cout << "february -> " << months["february"] << std::endl;
return 0;
}
Custom hash functionsTo use custom objects in std::unordered_map, a custom hash function must be defined. This function takes a const reference to the custom type and returns a size_t #include <unordered_map>
struct X{int i,j,k;};
struct hash_X{
size_t operator()(const X &x) const{
return std::hash<int>()(x.i) ^ std::hash<int>()(x.j) ^ std::hash<int>()(x.k);
}
};
The user defined function can be used as is in std::unordered_map, by passing it as a template parameter std::unordered_map<X,int,hash_X> my_map;
Or can be set as the default hash function by specializing the std::hash function 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;
References
|