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

void print(const auto& rg)
{
  for (const auto& elem : rg) {
    std::print("{} ", elem);
  }
  std::println("");
}

int main()
{
  std::vector<int> vec = {1, 2, 3, 4, 1, 2, 3, 4};
  std::list<int> lst = {1, 2, 3, 4, 1, 2, 3, 4};

  // some underlying ranges might not work:
  print(vec | std::views::drop(2));                               // OK
  print(lst | std::views::drop(2));                               // ERROR

  // some compositions might not work:
  print(vec | std::views::drop(1));                               // OK
  print(vec | std::views::lazy_split(3));                         // OK
  print(vec | std::views::drop(1) | std::views::lazy_split(3));   // OK
  print(vec | std::views::lazy_split(3) | std::views::drop(1));   // ERROR
}