Find last element in std::vector which satisfies a condition

Akshay Mathur picture Akshay Mathur · Aug 26, 2016 · Viewed 11.9k times · Source

I have this requirement to find the last element in the vector which is smaller than a value.

Like find_first_of but instead of first i want last. I searched and found that there is no find_last_of but there is find_first_of.

Why is that so? Is the standard way is to use find_first_of with reverse iterators?

Answer

rubenvb picture rubenvb · Aug 26, 2016

Use reverse iterators, like this:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> v{1,2,42,42,63};
  auto result = std::find_if(v.rbegin(), v.rend(),
                             [](int i) { return i == 42; });

  std::cout << std::distance(result, v.rend()) << '\n';
}

Live demo.