You can do it as follows. Suppose the container is std::vector<int> v
Then you can write something like
std::vector<int>::size_type i = 0; for ( int x : v ) {
for instance
#include <iostream> #include <vector> int main() { std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; std::vector<int>::size_type i = 0; for ( int x : v ) { std::cout << x << " is " << v[i] << std::endl; ++i; } }
However, there is a problem that the iterator must be a random access iterator. Otherwise, you cannot use the index operator.
source share