6

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.

daj
  • 6,962
  • 9
  • 45
  • 79
  • 1
    Do you mean s.th. like `for(auto it : enumerate())` – πάντα ῥεῖ May 03 '14 at 15:55
  • AFAIK there is no language feature to do this, and there isn't anything in the standard library you can trivially use. You would have to implement something, or use an ugly outer scope counter variable. – juanchopanza May 03 '14 at 16:00
  • @juanchopanza: What about an iteration variable that returns a tuple? – Robert Harvey May 03 '14 at 16:01
  • 2
    @RobertHarvey That would be filed under "implement something". You need a transformation from the container you want to iterate over to some kind of pair iterator. – juanchopanza May 03 '14 at 16:02
  • @juanchopanza: Sure, I was just kinda hoping to see something like that. I am disappoint. – Robert Harvey May 03 '14 at 16:04
  • 1
    You can implement `enumerate()` yourself so it's as easy as `for (auto &&iv : enumerate(listVar))`: http://coliru.stacked-crooked.com/a/f79bf773f4594ff1 – bames53 May 03 '14 at 16:44
  • [std::views::enumerate](https://en.cppreference.com/w/cpp/ranges/enumerate_view) is a C++23 solution. – Steve Ward Aug 09 '23 at 01:45

1 Answers1

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335