algo/findlast.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <print>
#include <vector>
#include <algorithm>

int main()
{
  
  std::array coll{8, 42, 7, 42, 15, 7};

  // find last element with the value 42 and return a subrange from there to the end:
  auto sub1 = std::ranges::find_last(coll, 42);
  std::println("{} sub with last 42: {}", coll, sub1);

  // find the last value that is a multiple of 3 and return a subrange from there to the end:
  auto times3 = [] (int val) { return val % 3 == 0; };
  auto sub2 = std::ranges::find_last_if(coll, times3);
  std::println("{} sub with last multiple of 3: {}", coll, sub2);

  // find the last even (not odd) value and return a subrange from there to the end:
  auto odd = [] (int val) { return val % 2 == 1; };
  auto sub3 = std::ranges::find_last_if_not(coll, odd);
  std::println("{} sub with last even: {}", coll, sub3);
}