Pratik Singhal
Pratik Singhal

Reputation: 6492

Is it possible to use custom find function in multimap?

I have a application which uses the multimap from STL in C++.

In multimap, I have to use find function with my custom function. ie Suppose, the contents of my multimap are {"Hello", "World"}, "{"Bye", "World"} and {"Foo", "Bar"}.

I want to search for the key which contains "e" in itself, ie the it should only return "Hello" and "Bye".

How can I do that ?

Basically, instead of the already defined find function which checks for the absolute equality, I want to define my own custom equality ?

Upvotes: 1

Views: 331

Answers (2)

Praetorian
Praetorian

Reputation: 109119

What you're looking for can be done, but not by using multimap::find. The multimap (or map) only performs lookups using the same comparator that you provide for key ordering, and it's not possible to use a different one only for (multi)map::find.

However, you can use copy_if to copy the key-value pairs you want to a different container.

std::multimap<std::string, std::string> m{{"Hello", "World"}, 
                                          {"Bye", "World"}, 
                                          {"Foo", "Bar"}};
std::vector<decltype(m)::value_type> vec;

std::copy_if(m.begin(), m.end(), std::back_inserter(vec),
    [](decltype(m)::value_type const& kv) {
        return std::any_of(kv.first.begin(), kv.first.end(), 
                           [](decltype(*kv.first.begin()) c) {return c == 'e';});
    });

vec will contain the key-value pairs you're interested in.

Live demo

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

A map(and multimap) in c++ is a datastructure optimized for searching by the key. However the search is performed using the comparison operator used when declaring the map. If you need to perform any search using a different comparison(in this case the letters contained in the key), you will not be able to make use of the good performance of the find operation. Your only option will be to perform linear search. Another option is to declare the map with a different(custom) comparison operator.

Upvotes: 4

Related Questions