C++ find first element in vector satisfying a condition using the std library

Viewed 5547

I have a vector containing objects, and each object has a method that returns a boolean. I would like to find the first element whose method returns true.

I know I could simply iterate over the vector using a for loop, but I'm looking for a solution that uses the std library.

Googling I found nothing, just the find and find_if functions, but that's not what I'm looking for. I'm looking for a function that basically takes a reference to the vector and a lambda and returns the first element for which the lambda returns true.

Note: I would also be interested in a function that returns an element, and not necessarily the first.

1 Answers

What you are looking for is std::ranges::find_if and you'll use it like

auto iterator = std::ranges::find_if(vector, lambda);

This does require C++20 support. If you don't have that, then use the plain old std::find_if like

auto iterator = std::find_if(vector.begin(), vector.end(), lambda);
Related