Search for a struct item in a vector by member data

This can be done with std::find_if and a search predicate, which can be expressed as a lambda function if you have C++11 (or C++0x) available:

auto pred = [](const Friend & item) {
    return item.ID == 42;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);

To use an ID given as a variable, you have to capture it in the lambda expression (within the [...]):

auto pred = [id](const Friend & item) {
    return item.ID == id;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);

If you don’t have C++11 available, you have to define the predicate as a functor (function object). Remy Lebeau’s answer uses this approach.

To remove elements matching the criteria as defined by the predicate, use remove_if instead of find_if (the rest of the syntax is the same).

For more algorithms, see the STL <algorithm> reference.

Leave a Comment