Home > Blockchain >  finding all the values with given key for multimap
finding all the values with given key for multimap

Time:07-03

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

CodePudding user response:

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

CodePudding user response:

Like others pointed out your code looped all the elements, from the first iterator (find(1) retuned the first iterator) to last.

If you want you can use C 20 ranges (#include <ranges>)

//DATA
std::multimap<int, int> mp;    
mp.insert({ 1,2 });
mp.insert({ 11,22 });
mp.insert({ 12,42 });
mp.insert({ 1,3 });
mp.insert({ 1,4 });

//FILTER THE ELEMENTS
auto foundElements = mp | std::views::filter([](auto& v) {
    return v.first == 1;
    });

//PRINT
for (auto m : foundElements)
{
    std::cout << m.first << " " << m.second << std::endl;
}
  • Related