Is there an analogue of C ++ / C ++ 11 for iterating python by index and value "for i, v in the enumeration (listVar):"?

Is there a C ++ analogue for the python idiom:

for i, v in enumerate(listVar): 

i.e. I want the iteration to have access to both the index and the value of the container that I iterated.

+6
source share
1 answer

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 ) { // using x; // using v[i]; ++i; } 

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.

+3
source

All Articles