2

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';
}
  • 1
    `find` returns an iterator into the map where the element is found. It doesn't create something new with just the matched results. – ChrisMM Jul 02 '22 at 18:47
  • This code must not do what you want it to do. But you haven't mentioned what you want it to do, and that makes it rather difficult to "solve this". The output is correct for the code you have written. – Drew Dormann Jul 02 '22 at 18:48
  • I want to search all the pairs with 1 as key. find(11) return {11,22} but it's not the case with find(1), it returns all the pairs. – 2k18_EC_157 Jul 02 '22 at 18:50
  • Your code is written to find one iterator with a `1` key - which it does - and then iterate to the end of the container - which it does. I suspect that you may be confused about what an iterator is (`itr`), or what it means to increment an iterator (`itr++`), or what `mp.end()` signifies. – Drew Dormann Jul 02 '22 at 18:51
  • @2k18_EC_157 The info you've posted in the comment is essential for understanding your actual problem+desired behaviour. If you notice there's confusion about what you're asking about, you should [edit] the question and add this info to the question itself. I've already added the info to the question in this case btw. – fabian Jul 02 '22 at 19:01

2 Answers2

6

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';
}
fabian
  • 80,457
  • 12
  • 86
  • 114
3

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;
}
Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34