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++?
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++?
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).
you can use the auto keyword and a range based for loop
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto const& e:v){
// here e is value from v
}
more info: https://en.cppreference.com/w/cpp/language/range-for
What about std::apply C++17 function:
std::apply([](auto&& v){ do_something_over_v();}, std::tie(v1,v2,v3) ) ;
If you don't have C++17, just copy implementation from reference -) , worked for C++14 mode, as I know.