Std :: unordered_map and duplicate keys

I am using stl unordered_map and I cannot get the count method to work. This is my program:

typedef unordered_map<char, int> Mymap; int main() { Mymap m; m.insert(Mymap::value_type('a', 1)); m.insert(Mymap::value_type('b', 2)); m.insert(Mymap::value_type('c', 3)); m.insert(Mymap::value_type('b', 4)); m.insert(Mymap::value_type('b', 5)); cout << m.count('b') << endl; return 0; } 

The documentation for unordered_map states that unordered_map::count(const Key& k) returns the number of elements with key k . Therefore, I expect the output here to be 3 , while the actual output will be 1 . Why?

+7
source share
2 answers

An unordered_map supports a 1: 1 key mapping for a value, so count will always return zero or one.

You need unordered_multimap if you want to match multiple values ​​with one key.

+27
source
 // g++ -std=c++0x init-unorderedmap.cc && ./a.out #include <iostream> #include <unordered_map> namespace { typedef std::unordered_map<char, int> Mymap; } int main() { using namespace std; Mymap m{ {'a', 1}, {'b', 2}, {'c', 3}, {'b', 4}, {'b', 5}}; cout << m.count('b') << endl; unordered_multimap<char, int> mm{ {'b', 4}, {'b', 5}}; cout << mm.count('b') << endl; } 

Exit

 1 2 
+10
source

All Articles