I know that STL has a HashMap API, but I cannot find any good and thorough documentation with good examples regarding this.
Any good examples will be appreciated.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The standard library includes the ordered and the unordered map (
std::mapandstd::unordered_map) containers. In an ordered map (std::map) the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map (std::unordered_map) insert and access is in O(1). It is just another name for a hashtable.An example with (ordered)
std::map:Output:
If you need ordering in your container and are fine with the O(log n) runtime then just use
std::map.Otherwise, if you really need a hash-table (O(1) insert/access), check out
std::unordered_map, which has a similar tostd::mapAPI (e.g. in the above example you just have to search and replacemapwithunordered_map).The
unordered_mapcontainer was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add-std=c++11to the CXXFLAGS).Even before the C++11 release GCC supported
unordered_map– in the namespacestd::tr1. Thus, for old GCC compilers you can try to use it like this:It is also part of boost, i.e. you can use the corresponding boost-header for better portability.