Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding all the values with given key for multimap

I am searching for all pairs for a particular key in a multimap using the code below.

int main() {
    multimap<int,int> mp;
    mp.insert({1,2});
    mp.insert({11,22});
    mp.insert({12,42});
    mp.insert({1,2});
    mp.insert({1,2});

    for (auto itr = mp.find(1); itr != mp.end(); itr++)
        cout << itr->first<< '\t' << itr->second << '\n';
}
like image 702
zodiac Avatar asked Jun 09 '26 19:06

zodiac


1 Answers

You're calling find only a single time in your code. It's perfectly acceptable for this call to return the same value as mp.begin() resulting in you iterating though all the entries in the map before reaching mp.end().

You can use the equal_range member function to get iterators for the start and end of the elements with key 1:

for (auto[itr, rangeEnd] = mp.equal_range(1); itr != rangeEnd; ++itr)
{
    std::cout << itr->first<< '\t' << itr->second << '\n';
}
like image 78
fabian Avatar answered Jun 12 '26 10:06

fabian