Daily C++ Tip 5

enumerate instead of a manual counter (C++23 ranges)

Enumerate pairs each element with its index, so no counter is maintained by hand.

std::views::enumerate pairs each element with its index, so the loop body never maintains a counter by hand.

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

int main() {
    std::vector<std::string> names{"ada", "grace", "linus"};
    // enumerate pairs each element with its index: no manual counter.
    for (auto [i, name] : std::views::enumerate(names)) {
        std::cout << i << ": " << name << '\n';
    }
}

Observed output:

0: ada
1: grace
2: linus

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.