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 exampleimport std;
const std::unordered_map<std::string, int> MONTHS {
{"January", 31},
{"February", 28},
{"March", 31},
{"April", 30},
{"May", 31},
{"June", 30},
{"July", 31},
{"August", 31},
{"September", 30},
{"October", 31},
{"November", 30},
{"December", 31}
};
int main(int argc, char* argv[]) {
std::println("September -> {}", MONTHS["September"]);
std::println("April -> {}", MONTHS["April"]);
std::println("December -> {}", MONTHS["December"]);
std::println("February -> {}", MONTHS["February"]);
return 0;
}
Custom hash functionsTo use custom objects in import std;
struct Vector3 {
int i;
int j;
int k;
};
struct HashVector3 {
size_t operator()(const Vector3& 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<Vector3, int, HashVector3> myPointToIntMap;
Or can be set as the default hash function by specializing namespace std {
template <>
class hash<Vector3> {
public:
size_t operator()(const Vector3& x) const {
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
}
};
}
//...
std::unordered_map<Vector3, int> myPointToIntMap;
References
|