Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++/C++11 analogue to python iteration over both index and value "for i, v in enumerate(listVar):"? [duplicate]

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

for i, v in enumerate(listVar):

i.e. I want to iterate with access to both the index and the value of the container I'm iterating over.

like image 793
daj Avatar asked May 03 '14 15:05

daj


1 Answers

You can do it the following way. Let assume that the container is std::vector<int> v

Then you can write something as

std::vector<int>::size_type i = 0;

for ( int x : v )
{
   // using x;
   // using v[i];
   ++i;
}

For example

#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 shall be a random access iterator. Otherwise you may not use the subscript operator.

like image 131
Vlad from Moscow Avatar answered Oct 26 '22 16:10

Vlad from Moscow