ranges/chunkbycaching.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 <cmath>
#include <ranges>

int main()
{
  std::vector coll{1, 2, 3, 4};
  coll.reserve(100);
  auto allEvenOrOdd = [] (auto x, auto y) {
    return std::abs(x % 2) == std::abs(y % 2);
  };

  // initialize views:
  auto v1 = coll | std::views::chunk_by(std::less{});
  auto v2 = coll | std::views::chunk_by(allEvenOrOdd);

  // apply views:
  std::println("coll:       {} =>", coll);
  std::println("  less:     {}", v1);
  std::println("  even/odd: {}\n", v2);

  // modify underlying range:
  coll.insert(coll.begin(), -1);

  // apply views again:
  std::println("modified:   {} =>", coll);
  std::println("  less:     {}", v1);
  std::println("  even/odd: {}\n", v2);

  // create new views and apply them:
  auto coll2 = coll;
  auto v3 = coll | std::views::chunk_by(std::less{});
  auto v4 = coll | std::views::chunk_by(allEvenOrOdd);
  std::println("new views:  {} =>", coll);
  std::println("  less:     {}", v3);
  std::println("  even/odd: {}\n", v4);
}