Python-like Enumeration in C++11

“Range-based for loops in C++11 are a nice addition to the language. However, there is still no support in the STL for enumerating items in a container without creating an extra counter variable that must be incremented separately from the looping variable:

std::list<int> list = { 1, 2, 3, 4, 5, 6, 7 };

int index = 0;  // this is outside the loop block although only used inside it
for (auto x : list)
{
    cout << index << " " << x << endl;
    index ++;  // this has to be incremented manually; error-prone in more complex loop logic
}

Note that the index is not to access the items in the container; it is to keep track of how many items have been processed so far in the loop.

I would like to be able to enumerate items in an STL container as simply as it can be done in Python, i.e. via a generic “enumerate()“:

# Python code: 
list = { "a", "b", "c", "d", "e", "f" }

for index, x in enumerate(list):
    print(index, x)

In C++11, it could look like this:

std::list<int> list = { 1, 2, 3, 4, 5, 6, 7 };

for (auto x : enumerate(list))
    cout << x.index << " " << x.value << endl;

This is concise and clear. The next section provides some background. The main section shows the code that supports the above syntax and more. Finally, some possible extensions…”

http://www.codeproject.com/Tips/1029941/Python-like-Enumeration-in-Cplusplus

Advertisements