finding all the values with given key for multimap
Asked Answered
E

2

5

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';
}
Editorial answered 2/7, 2022 at 18:45 Comment(5)
find returns an iterator into the map where the element is found. It doesn't create something new with just the matched results.Deciliter
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.Glean
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.Editorial
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.Glean
@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.Sciatica
S
10

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';
}
Sciatica answered 2/7, 2022 at 18:53 Comment(1)
this is what i was looking for. Thanks. My mistake, I misunderstood the find function.Editorial
P
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;
}
Puny answered 2/7, 2022 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.