5

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++?

heracho
  • 590
  • 1
  • 9
  • 28
  • If you are able to use C++11 or higher, you can use [range for loop](http://en.cppreference.com/w/cpp/language/range-for). – R Sahu Jun 07 '18 at 18:45
  • 6
    I do not see why people are closing this question, it is a valid question. – SergeyA Jun 07 '18 at 18:45
  • You should also read: https://stackoverflow.com/questions/15927033/what-is-the-correct-way-of-using-c11s-range-based-for – NathanOliver Jun 07 '18 at 18:48
  • Possible duplicate of [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) –  Jun 07 '18 at 18:56

3 Answers3

8
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).

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • 1
    Unfortunately, not entirely - those variables are going to be copied into initializer list (at least semantically), so copy constructor has to be available. – SergeyA Jun 07 '18 at 18:48
  • @SergeyA Fair point. It's the closest equivalent *I* could think of. If you have a closer one, please post an answer and I'll upvote that and delete this one. – Jesper Juhl Jun 07 '18 at 18:50
  • 1
    I do not know of any closer one which would be that concise, and I have a feeling it will not necessarily matter for OP, I just think you might want to make a note of that in your answer. – SergeyA Jun 07 '18 at 18:53
  • I think I'm not using C++11: "range-based 'for' loops only available with -std=c++11" – heracho Jun 07 '18 at 19:11
  • 1
    @heracho then I would advise getting up-to-date with the latest C++ version (currently C++17) :-) You *can* do the same thing in C++98, it just won't be nearly as concise, nor as readable. – Jesper Juhl Jun 07 '18 at 19:23
6

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

Grant Williams
  • 1,469
  • 1
  • 12
  • 24
1

What about std::apply C++17 function:

std::apply([](auto&& v){ do_something_over_v();}, std::tie(v1,v2,v3) ) ;
  • Needn't copy of v1, v2, v3 elements, just took reference of them.
  • Needn't require to identity type of v1, v2, v3.

If you don't have C++17, just copy implementation from reference -) , worked for C++14 mode, as I know.

reference to std::apply