Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_multimap - iterating the result of find() yields elements with different value

The multimap in C++ seems to work really odd, i would like to know why

#include <iostream>
#include <unordered_map>

using namespace std;

typedef unordered_multimap<char,int> MyMap;

int main(int argc, char **argv)
{
    MyMap map;
    map.insert(MyMap::value_type('a', 1));
    map.insert(MyMap::value_type('b', 2));
    map.insert(MyMap::value_type('c', 3));
    map.insert(MyMap::value_type('d', 4));
    map.insert(MyMap::value_type('a', 7));
    map.insert(MyMap::value_type('b', 18));

    for(auto it = map.begin(); it != map.end(); it++) {
        cout << it->first << '\t';
        cout << it->second << endl;
    }

    cout << "all values to a" << endl;
    for(auto it = map.find('a'); it != map.end(); it++) {
        cout << it->first << '\t' << it->second << endl;
    }

}

this is the output:

c   3
d   4
a   1
a   7
b   2
b   18
all values to a
a   1
a   7
b   2
b   18

why does the output still contain anything with b as the key when I am explicitly asking for 'a'? Is this a compiler or stl bug?

like image 271
Arne Avatar asked Jan 28 '12 16:01

Arne


People also ask

What is unordered_ multimap in c++?

} (2) (since C++17) Unordered multimap is an unordered associative container that supports equivalent keys (an unordered_multimap may contain multiple copies of each key value) and that associates values of another type with the keys. The unordered_multimap class supports forward iterators.

Can unordered_map have duplicate values?

Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.


1 Answers

find, as implemented, returns an iterator for the first element which matches the key in the multimap (as with any other map). You're likely looking for equal_range:

// Finds a range containing all elements whose key is k.
// pair<iterator, iterator> equal_range(const key_type& k)
auto its = map.equal_range('a');
for (auto it = its.first; it != its.second; ++it) {
    cout << it->first << '\t' << it->second << endl;
}
like image 85
user7116 Avatar answered Oct 11 '22 08:10

user7116