Skip to content
C++ Basics: Fill an Existing Buffer with Consecutive Values

C++ Basics: Fill an Existing Buffer with Consecutive Values

November 8, 2026

Use iota to populate an existing integer range with a sequence starting at a chosen value.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as iota-index-sequence-demo.cpp:

#include <iostream>
#include <numeric>
#include <vector>

int main()
{
    std::vector<int> ids(4);
    std::iota(ids.begin(), ids.end(), 10);
    std::cout << "ids:";
    for (int id : ids) std::cout << ' ' << id;
    std::cout << '\n';
    std::vector<int> empty;
    empty.reserve(4);
    std::iota(empty.begin(), empty.end(), 10);
    std::cout << "reserved-only size: " << empty.size() << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic iota-index-sequence-demo.cpp -o iota-index-sequence-demo &&
./iota-index-sequence-demo

Observed output:

ids: 10 11 12 13
reserved-only size: 0

Read the result

The sized vector receives 10 through 13. reserve increases capacity but creates no elements, so the second iota call processes an empty range and its vector stays empty.

Apply it carefully

iota assigns to existing elements and increments a local copy of its starting value. It does not append. The increment uses the type of the starting argument, not the destination type. Choose a type and starting value whose increments remain representable, including the increment performed after the final assignment; signed overflow is undefined behavior.

The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- iota-index-sequence-demo.cpp iota-index-sequence-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on