Search code examples
c++c++11multimap

Search for value in multi map


Suppose I have the following:

class Foo {
public:
    Foo(int x) {
        _x = x;
    }
    int _x;    
}

int main() {
    multimap<string, Foo> mm;
    Foo first_foo(5);
    Foo second_foo(10);

    mm.insert(pair<string, Foo>("A", first_foo));
    mm.insert(pair<string, Foo>("A", second_foo));

    Foo third_foo(10); 
}

What's a nice way of checking if third_foo with key "A" is already in my multimap?


Solution

  • Use multimap::equal_range to fetch a range of iterators to entries that have the key "A". Then use any_of to check if any of those values compare equal to the Foo you want.

    auto const& r = mm.equal_range("A");
    bool found = std::any_of(r.first, r.second,
                             [&third_foo](decltype(mm)::value_type const& p) {
                                 return p.second._x == third_foo._x;
                             });