Reputation: 2665
I'm using an stl unordered_map, and I can't seem to 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 says that unordered_map::count(const Key& k)
returns the number of elements with the key k
.
So I would expect the output here to be 3
, whereas the real output is 1
. Why?
Upvotes: 14
Views: 40697
Reputation: 414149
// 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;
}
1
2
Upvotes: 14
Reputation: 355039
An unordered_map
maintains a 1:1 mapping of key to value, so count
will always return zero or one.
You need an unordered_multimap
if you want to map multiple values to a single key.
Upvotes: 38