Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL <map> allows duplicate pairs?

Tags:

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?

like image 844
dead programmer Avatar asked May 24 '12 06:05

dead programmer


People also ask

Can a std::map have duplicate keys?

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.

Does map allow duplicate keys in CPP?

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.

Can there be duplicates in a map?

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.

How do you keep keys duplicated in maps?

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!


2 Answers

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; 
like image 176
NPE Avatar answered Nov 07 '22 09:11

NPE


STL map does not allow same Keys to be used. You may want to go for multi-map for that.

like image 44
Jay D Avatar answered Nov 07 '22 09:11

Jay D