STL <map> allows duplicate pairs?
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. but in the below case it will be overwritten.
map<char,int> m1;
m1.insert(pair <char, int> ('a', 40));
m1['a']=50;
cout << "a => " << m1.find('a')->second << '\n';
The result will be 50.
below example, it will not overwrite.
map<char,int> m1;
m1.insert(pair <char, int> ('a', 40));
m1.insert(pair <char, int> ('a', 50));
cout << "a => " << m1.find('a')->second << '\n';
Result will be 40.
Remember map size 1 here for both the cases.
cout< "size = " << m1.size() << '\n';
it will be 1 in both cases.
STL map does not allow same Keys to be used. You may want to go for multi-map for that.
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;