in Java, we´ve got methods like hashCode() and equals() which are used by the map to identify each object. C++ doesn´t have such basic methods, each object implements by default.
How can a map now use custom objects as the key value?
Edit: No duplicate because it´s especially aiming towards those java specific interface methods, someone who has nothing done before with C++ would look for
Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys.
Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.
Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.
First, a std::map
in C++ is generally a red black tree, not a hash table. There is also a hash map in C++11 called std::unordered_map
. By default it uses operator<
to compare elements. You can also plug in a custom comparator which can compare using anything you want. This is done by using the optional 3rd template argument to std::map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With