Python 循环的 C++ 版本“for i, num in enumerate(list):”

Ben*_*Ben 4 c++ python enums

在 python 中,您可以迭代一个列表,如下所示。在 C++ 中是否有类似的简短方法可以做到这一点?

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

likefor(int num : list)很接近,但不一样。

小智 10

C++17次!

for(auto [it, i] = tuple{list.begin(), 0}; it != list.end(); it++, i++)
{
   cout << *it; //actual item
   cout << i; //index value
}
Run Code Online (Sandbox Code Playgroud)