ranges/views3.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 <chrono>
#include <ranges>

constexpr bool isPrime(int value)
{
  for (int i = 2; i <= value/2; ++i) {
    if (value % i == 0) {
      return false;
    }
  }
  return value > 1;  // 0 and 1 are not prime numbers
}

int main()
{
  auto asSeconds = [] (auto val) {
    return std::chrono::seconds{val};
  };

  // view of 4th to 11th prime numbers as seconds:
  auto vPrimes = std::views::iota(1)                   // generates 1, 2, 3, ...
                  | std::views::filter(isPrime)        // only prime numbers
                  | std::views::drop(3)                // skip first 3
                  | std::views::take(8)                // take next 8
                  | std::views::transform(asSeconds);  // as seconds

  std::println("{}", vPrimes);
}