Question About find_if

Hello,

I'm trying to find an element in a vector using find_if. If I had a vector<string>, I would do this:

auto it = find_if(v.begin(), v.end(), bind2nd(equal_to<string>(), name));

But I have a vector of a class C which has a member function called getName. I am trying to figure out how I create something analogous. I have already read about mem_fun_ref, but I still have no idea.

Thank you.
I asume you would replace equal_to<string> (or even the whole bind2nd clause) with your function that compares to the return of getName().

http://www.cplusplus.com/reference/algorithm/find_if/

See Cubbi's post below.
Last edited on
Since you have C++11 (based on "auto"), you could use the lambda:

1
2
3
auto p = std::find_if(v.begin(), v.end(),
                [&](const C& c){ return c.getName() == name;}
             );

or write your own functor.

(incidentally, bind2nd and mem_fun_ref are all deprecated in C++11, in favor of bind and mem_fn, which you can use too, but it's a bit more wordy:


1
2
3
4
5
6
 auto p = std::find_if(v.begin(), v.end(),
                std::bind(
                    std::equal_to<std::string>(), name,
                        std::bind(&C::getName, _1)
                )
             );

demo http://liveworkspace.org/code/f758c1765d56485a37500f3b63af0997

PS: as a bit of trivia, this kind of composition of function adaptors was possible in the STL, but it wasn't accepted in C++98.
Last edited on
Also you can define the equality operator that compares an object of your class with a string. In this case you need change nothing in your original code.:)
Last edited on
Topic archived. No new replies allowed.