Late as always :), but I'm here.
C++20 introduces syntax for the initializer-statement in range-based for loops. This initialization may either a simple-declaration, or an expression-statement. (The current working draft of C++23 also makes it possible to write an type-alias-declaration instead).
For a iterator, or a index, simply do something similar like the following:
std::vector<int> vec;
for (auto it = vec.begin(); auto& elem: vec) {
// ...
it++;
}
for (int i = 0; auto& elem: vec) {
// ...
i++;
}
This fixes the issue of scope of the outside variable method which @nawaz mentioned.
To note: expressions of that sort aren't limited to only one initialization, and there are also plenty of cool things that can be done inline. Examples:
// This will only be useful for containing a complex typedef's scope inside
// a for-loop, and I would say, is a smell that your typing system is not too
// developed.
for(typedef std::vector<std::vector<int>> Matrix; Matrix& m: container) {
// ...
}
// Good old (or rather, very new) one liner.
for(MyType my_instance(x,y,z); auto& elem: my_instance) {
// ...
}