Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unordered_map and duplicate keys

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?

like image 724
Bee San Avatar asked Nov 14 '11 17:11

Bee San


People also ask

Are duplicate keys allowed in unordered_map?

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 ...

Can map have duplicate keys c++?

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.

Are Keys sorted in unordered_map?

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.

Can unordered_set have duplicate values?

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.


1 Answers

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.

like image 60
James McNellis Avatar answered Oct 13 '22 03:10

James McNellis