STL <map> allows duplicate pairs?

c++, dictionary, stl

Solution

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;

Problem

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?

Original source