Suppose you want to know the numerical index of an element when iterating a container that doesn't offer random access iterators. For example:
std::list<std::string> items;
int i = 0;
for (auto & item : items) item += std::to_string(i++);
Is there a more idiomatic or nicer way of doing this? I presume this pattern comes up in various situations. I don't like the integer index being available outside of the loop. Bracketing the loop and the index definition in a local block seems ugly, too.
Of course when the container offers random access iterators, one can leverage the iterator difference, but then you can't use the range-for:
std::vector<std::string> items;
for (auto it = items.begin(); it != items.end(); ++it)
*it += std::to_string(it - items.begin());
Although I only show a C++11 example, I'm looking for hints for C++0x and C++98 as well.