Python-Like enumerate() In C++17--Nathan Reed

Save to:
Instapaper Pocket Readability

Handy little piece of code.

Python-Like enumerate() In C++17

by Nathan Reed

From the article:

Python has a handy built-in function called enumerate(), which lets you iterate over an object (e.g. a list) and have access to both the index and the item in each iteration. You use it in a for loop, like this:

for i, thing in enumerate(listOfThings):
    print("The %dth thing is %s" % (i, thing))

Iterating over listOfThings directly would give you thing, but not i, and there are plenty of situations where you’d want both (looking up the index in another data structure, progress reports, error messages, generating output filenames, etc).

C++ range-based for loops work a lot like Python’s for loops. Can we implement an analogue of Python’s enumerate() in C++? We can!

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.