C++ by default provides a tree based map. With Boost you can get a hashmap.
What are the advantages and disadvantages of
-
C++’s Tree Based Map and
-
Boost’s Hashmap
?
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.
C++0x/TR1 also provides the
unordered_mapwhich is usually implemented as a hash map.The differences are twofold:
The key type. In the ordered map, the key type must obey a strict weak ordering, and entries are maintained in that order. In the unordered map, the key type must be equality-comparable and you must provide a hash function
hsuch thath(Key)returnssize_t[thanks to Steve Jessop for the clarification].Access complexity: Insert/delete/find in an ordered map is O(log n) in the map size n. In the unordered map, it is “usually” O(1), but worst-case behaviour is O(n) (e.g. if all keys map to the same hash value).
So the ordered map provides a total complexity guarantee, while the unordered map provides a (better) complexity in good cases, depending on the quality of your hash function.
The internal implementation complexity of the unordered map is greater than of the ordered map, but you can imagine that you get the better access complexity because you get fewer features, i.e. you don’t get sorting for free. It’s a classical trade-off.
Another point: Practically, if the weak ordering operator is expensive to compute, like for strings, the unordered map may actually be quite a bit faster, because comparisons on the hash type are very fast. On the other hand, if your key type is one with trivial hash function (like any built-in integral type) and if you don’t need the ordering, consider using an unordered container.