Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 482
Akshay Mathur Avatar asked Aug 26 '16 11:08

Akshay Mathur


2 Answers

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.

like image 131
rubenvb Avatar answered Sep 20 '22 23:09

rubenvb


This is how it is done with reverse iterators:

std::vector<int> vec = {2,3,10,5,7,11,3,6};  

//below outputs '3':
std::cout << *(std::find_if(vec.rbegin(), vec.rend(), [](int i) { return i < 4; })); 
like image 43
Smeeheey Avatar answered Sep 21 '22 23:09

Smeeheey