std::ranges::iota — fill range with sequential values.
1#include <ranges>23std::vector<int> v(5);45// Fill with 0, 1, 2, 3, 46std::ranges::iota(v, 0);7// v = {0, 1, 2, 3, 4}89// Start from any value10std::ranges::iota(v, 10);11// v = {10, 11, 12, 13, 14}1213// Works with any output range14std::array<int, 5> arr;15std::ranges::iota(arr, 100);16// arr = {100, 101, 102, 103, 104}1718// With custom type19std::vector<char> chars(5);20std::ranges::iota(chars, 'A');21// chars = {'A', 'B', 'C', 'D', 'E'}2223// Combine with views24std::vector<int> result(10);25std::ranges::iota(result, 1);26auto squares = result27 | std::views::transform([](int x) { return x * x; });28// 1, 4, 9, 16, 25, 36, 49, 64, 81, 1002930// Compile-time31std::array<int, 5> arr2;32constexpr auto iota_arr = [] {33 std::array<int, 5> a;34 std::ranges::iota(a, 1);35 return a;36}();37// iota_arr = {1, 2, 3, 4, 5}
Benefits: