I have written the following code and was surprised at the output. I heard that <map>
avoids collision of keys, but here it appears to allow insertion of duplicate pairs.
#include<iostream> #include<map> using namespace std; int main() { map<string,char> namemap; namemap["yogi"]='c'; namemap.insert(pair<string,char>("yogendra",'a')); namemap.insert(pair<string,char>("yogendra",'b')); cout<<namemap["yogendra"]<<endl; return 0; }
This code outputs a
. You can run it on C++ Shell.
Does avoiding collision means that we cannot enter multiple pairs with same key?
a map will not throw any compile/run time error while inserting value using duplicate key. but while inserting, using the duplicate key it will not insert a new value, it will return the same exiting value only. it will not overwrite.
C++ Software Engineering Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.
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. Both HashSet and HashMap are not synchronized.
You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!
The second insert
with the same key is a no-op. It simply returns an iterator pointing to the existing element.
std::map::insert()
has a return value, which you should check.
It is of type std::pair<iterator,bool>
. The second element of the pair tells you whether the element has been inserted, or whether there was already an existing entry with the same key.
cout << namemap.insert(pair<string,char>("yogendra",'a')).second << endl; cout << namemap.insert(pair<string,char>("yogendra",'b')).second << endl;
STL map does not allow same Keys to be used. You may want to go for multi-map for that.
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