Lazy Evaluation
Understand the use of 'std::views::iota' with examples.
We'll cover the following...
We'll cover the following...
std::views::iota is a range factory for creating a sequence of elements by successively incrementing an initial value. This sequence can be finite or infinite.
Filling vector with views::iota
The following program fills a std::vector with int’s, starting with .
The first iota call (line 12) creates all numbers from to , incremented by . The second iota call (line 14) creates an infinite data stream, starting with , incremented by . std::views::iota(0) is lazy. I only get a new value if I ask for it. I ask for it ten times. Consequently, both vectors are identical.
Another example
Now, I want to solve a small challenge: finding the first prime numbers starting with .
This is my iterative strategy:
- line 14: Of course, I don’t know when I have primes greater than . To be on the safe side, I create numbers. For obvious reasons, I displayed only each th.
- line 24: I’m only interested in the odd numbers; therefore, I remove the even numbers.
- line 31: Now, it’s time to apply the next filter. The predicate
isPrime(line 4) returns if a number is prime. As you can see from the output of the program, I was too eager. I got primes. - line 39: Laziness is a virtue. I use
std::iotaas an infinite number factory, starting with and ask precisely for primes.