8 Key Standard Library Algorithms

Using std::iota() with a Custom Step Size

How can I use std::ranges::iota() to generate a sequence with a custom step size?

To generate a sequence with a custom step size using std::ranges::iota(), you will need to create a custom range by combining std::views::iota with a std::views::transform view.

This approach allows you to apply a transformation to each element in the generated sequence.

Here's an example that generates a sequence with a step size of 2:

#include <iostream>
#include <ranges>
#include <vector>

int main() {
auto custom_range = std::views::iota(1)
| std::views::transform([](int n) {
return n * 2;
});

// Take the first 10 elements
std::vector<int> sequence(
custom_range.begin(),
custom_range.begin() + 10
);

for (int n : sequence) {
std::cout << n << ", ";
}
}
2, 4, 6, 8, 10, 12, 14, 16, 18, 20,

In this example, std::views::iota(1) generates an infinite range starting from 1. The std::views::transform view applies a lambda function to each element, multiplying it by 2. The result is a sequence with a step size of 2.

You can also generate sequences with other custom step sizes by modifying the lambda function. For example, to generate a sequence with a step size of 3:

#include <iostream>
#include <ranges>
#include <vector>

int main() {
auto custom_range = std::views::iota(1)
| std::views::transform([](int n) {
return n * 3;
});

// Take the first 10 elements
std::vector<int> sequence(
custom_range.begin(),
custom_range.begin() + 10
);

for (int n : sequence) {
std::cout << n << ", ";
}
std::cout << "\n";
}
3, 6, 9, 12, 15, 18, 21, 24, 27, 30,

By combining std::views::iota with std::views::transform, you can create sequences with any custom step size. This method is flexible and allows you to apply various transformations to the generated elements.

Using views in this way leverages the power of ranges to create complex sequences with minimal code, making your programs more readable and expressive.

This Question is from the Lesson:

8 Key Standard Library Algorithms

An introduction to 8 more useful algorithms from the standard library, and how we can use them alongside views, projections, and other techniques

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

8 Key Standard Library Algorithms

An introduction to 8 more useful algorithms from the standard library, and how we can use them alongside views, projections, and other techniques

Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

• 124 Lessons
• 550+ Code Samples
• 96% Positive Reviews
• Regularly Updated
• Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.