Search code examples
c++hashmultimap

c++ hash_multimap how to get the values


This is probably really simple, but I can't find a simple example for it. I understand that with a hash_multimap you can have several values mapped to a single key. But how exactly would I access those values. All the examples I stumbled across always just access the first value mapped to the the key. Heres an example of what I mean

key : value
1 : obj1a;
2 : obj2a, obj2b, obj2c

how would I access obj2b and obj2c, not just obj2a


Solution

  • The usual multimap iteration loop is like this:

    #include <unordered_multimap>
    
    typedef std::unordered_multimap<K, V> mmap_t;
    
    mmap_t m;
    
    for (mmap_t::const_iterator it1 = m.begin(), it2 = it1, end = m.end(); it1 != end; it1 = it2)
    {
        // outer loop over unique keys
    
        for ( ; it1->first == it2->first; ++it2)
        {
            // inner loop, all keys equal to it1->first
        }
    }
    

    To iterate over just one key value, use equal_range instead.

    std::pair<mmap_t::const_iterator, mmap_t::const_iterator> p = m.equal_range(key);
    
    for (mmap_t::const_iterator it = p.first; it != p.second; ++it)
    {
        // use "it->second"
    }