Search⌘ K
AI Features

Lazy Evaluation

Learn how to use lazy evaluation with std::views::iota in the C++20 ranges library to generate finite and infinite sequences. Understand how to filter and process these sequences efficiently, demonstrated by finding prime numbers starting from a large initial value.

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 1010 int’s, starting with 00.

C++
#include <iostream>
#include <numeric>
#include <ranges>
#include <vector>
int main() {
std::cout << std::boolalpha;
std::vector<int> vec;
std::vector<int> vec2;
for (int i: std::views::iota(0, 10)) vec.push_back(i);
for (int i: std::views::iota(0) | std::views::take(10)) vec2.push_back(i);
std::cout << "vec == vec2: " << (vec == vec2) << '\n';
for (int i: vec) std::cout << i << " ";
}

The first iota call (line 12) creates all numbers from 00 to ...