Back to TILs

C++ ranges 04

Date: 2023-03-10Last modified: 2024-11-02

Table of contents

int main() {
  std::vector<int> v(1000000);
  std::iota(v.begin(), v.end(), 1);

  // clang-format off
  auto even_squares = v 
    | std::views::filter([](int x) { return x % 2 == 0; })
    | std::views::filter([](int x) { return x <= 20; })
    | std::views::transform([](int x) { return x * x; });
  // clang-format on

  std::cout << "Even squares:\n";
  for (auto x : even_squares) {
    std::cout << x << "\n";
  }
  std::cout << "\n";

  return 0;
}

Possible output

Even squares:
4
16
36
64
100
144
196
256
324
400


References