core/autoviews.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 <list>
#include <ranges>

int main()
{
  std::list values{0, 8, 15, 47, 11, 1};  
  std::println("values:  {}", values);

  // init views with every second element of values:
  auto v2ndRef = values | std::views::stride(2);         // refer to values
  auto v2ndCpy = auto{values} | std::views::stride(2);   // copy values

  std::println("v2ndRef: {}", v2ndRef);
  std::println("v2ndCpy: {}\n", v2ndCpy);

  // modify values:
  values.push_front(7);
  std::println("values:  {}", values);

  std::println("v2ndRef: {}", v2ndRef);                  // modified
  std::println("v2ndCpy: {}\n", v2ndCpy);                // as before
}