4

In python, you can iterate a list like below. Is there a similarly short way of doing this in C++?

list = [1,2,3,4,5]
for i, num in enumerate(list):
     # do stuff

Something like for(int num : list) is close, but not the same.

Ben
  • 321
  • 1
  • 6
  • 21
  • 2
    Is this what you could use? https://stackoverflow.com/questions/11328264/python-like-loop-enumeration-in-c – incapaz Oct 14 '19 at 15:12

1 Answers1

10

C++ 17 time!

for(auto [it, i] = tuple{list.begin(), 0}; it != list.end(); it++, i++)
{
   cout << *it; //actual item
   cout << i; //index value
}
Sam Brightman
  • 2,831
  • 4
  • 36
  • 38
Arpan Arpan
  • 136
  • 1
  • 6