ranges/viewsgen.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 <iostream>
#include <random>
#include <generator>
#include <ranges>

// coroutine that generates random values:
std::generator<int> generateRandom()
{
  // init random number generator with random initial state:
  std::default_random_engine engine{std::random_device{}()};

  // init a distribution of values from 1 to 100:
  std::uniform_int_distribution<int> intDist{1, 100};

  // yield endless sequence of random values between 1 and 100:
  while (true) {
    co_yield intDist(engine);    // SUSPEND the coroutine with the next generated value
  }
}

int main()
{
  // iterate over the first 20 values generated by the coroutine view generateRandom():
  for (const auto& val : generateRandom() | std::views::take(20)) {
    std::cout << val << ' ';
  }
  std::cout << '\n';
}