ranges/viewrefsem.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 <ranges>
#include <algorithm>

int main()
{
  std::vector coll{1, 2, 3, 4, 5, 6, 7, 8};
  std::println("coll:      {}", coll);

  // print every second element (view referring to coll as whole):
  auto every2nd = coll | std::views::stride(2);
  std::println("every 2nd: {}", every2nd);
  
  // print all elements before 5 (view holding iterators to coll):
  std::ranges::subrange sub{coll.begin(), std::ranges::find(coll, 5)};
  std::println("before 5:  {}\n", sub);

  coll.push_back(42);    // NOTE: invalidates sub (because reallocation invalidates iterators)

  std::println("coll:      {}", coll);       // OK
  std::println("every 2nd: {}", every2nd);   // OK
  std::println("before 5:  {}\n", sub);      // ERROR: undefined behavior
}