ranges/adjacenttransformview.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 <string>
#include <vector>
#include <ranges>

int main()
{
  std::vector<int> coll{47, 11, 0, 8, 15, 14, 13};
  std::println("{}", coll);

  auto diff = [](auto a, auto b) { return b - a; };
  for (auto val : coll | std::views::adjacent_transform<2>(diff)) {
    std::print("{} ", val);
  }
  std::println("");

  auto avg = [](auto a, auto b, auto c) { return (a + b + c) / 3.0; };
  for (auto val : coll | std::views::adjacent_transform<3>(avg)) {
    std::print("{:.3f} ", val);
  }
  std::println("");
}