Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Map in C++ as a Java developer [duplicate]

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

like image 767
Marian Klühspies Avatar asked Jan 14 '14 17:01

Marian Klühspies


People also ask

Does map in Java allow duplicates?

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.

How can I tell if a map has duplicate 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.

Which map in Java allows duplicate keys?

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.


1 Answers

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.

like image 180
David Avatar answered Sep 27 '22 18:09

David