Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate in C++ like in python

Tags:

c++

python

loops

I would like to iterate in C++ over a set of values. In python, it looks like

for v in [v1, v2, v3]:
    do_something()

What is the correct way to do it in C++?

like image 329
heracho Avatar asked Jun 07 '18 18:06

heracho


People also ask

How do you write a for loop like C in Python?

for i in range(0,len(argv)): arg = argv[i] if arg == '--flag1': opt1 = argv[i+1] i+=1 continue if arg == '--anotherFlag': optX = argv[i+1] optY = argv[i+2] optZ = argv[i+3] i+=3 continue ...

Why for loop is different in Python?

For loop allows a programmer to execute a sequence of statements several times, it abbreviates the code which helps to manage loop variables. While loop allows a programmer to repeat a single statement or a group of statements for the TRUE condition. It verifies the condition before executing the loop.


1 Answers

for (const auto& v : {v1, v2, v3}) { do_something(); }

Would be equivalent (except for the fact that the elements in the initializer list will conceptually be copied - even if the optimizer elides those copies - so they will need to be copyable).

like image 125
Jesper Juhl Avatar answered Sep 23 '22 19:09

Jesper Juhl