C++ - enumerate with ranges library

less than 1 minute read

C++’s Ranges library enables enumeration of containers with access to both indices and elements.

✅ Option 1: Standard C++23 (No enumerate, use zip + iota)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <map>
#include <ranges>
#include <utility> // for std::as_const

int main() {
    std::map<std::string, int> scores = {
        {"Alice", 90},
        {"Bob", 85},
        {"Charlie", 78}
    };

    // Enumerate using iota + zip
    for (auto [index, pair] : std::views::zip(std::views::iota(0), std::as_const(scores))) {
        std::cout << index << ": " << pair.first << " => " << pair.second << '\n';
    }

    return 0;
}

✅ Option 2: Using range-v3’s views::enumerate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <range/v3/all.hpp>
#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> scores = {
        {"Alice", 90},
        {"Bob", 85},
        {"Charlie", 78}
    };

    for (auto [index, pair] : ranges::views::enumerate(std::as_const(scores))) {
        std::cout << index << ": " << pair.first << " => " << pair.second << '\n';
    }

    return 0;
}

Categories:

Updated: