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?
We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to ...
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.
Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets.
Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - However, they can be inserted and removed. Unordered sets do not allow duplicates and are initialized using comma-delimited values enclosed in curly braces.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With