std::unordered_map and duplicate keys

28,950

Solution 1

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.

Solution 2

// 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;
}

Output

1
2
Share:
28,950
Bee San
Author by

Bee San

Updated on July 05, 2022

Comments

  • Bee San
    Bee San almost 2 years

    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?

  • Paul Manta
    Paul Manta over 12 years
    That's odd. Why does that function exist then? If you use it to check if a key exists in the map, why not just use the traditional way, find(...) != end()?
  • Bee San
    Bee San over 12 years
    Indeed - the name count() is misleading. exists() would be better.
  • James McNellis
    James McNellis over 12 years
    count() is part of the interface for all associative containers.
  • jfs
    jfs over 12 years
    @Paul Manta: map is a unique associative container so m.count() returns either 0 or 1. But for an associative container in general such as multiset, multimap it can return values greater than 1.