0

I understand how to use a for loop like

for (x = 0 ; x<5 ; x++ ) { // some_code }

in C++ but what about a for loop like

for x in y:

which exist at least in python

1
  • 3
    Are you asking, how does one iterate over a container in C++ in the same way? Commented Mar 3, 2014 at 21:12

3 Answers 3

6

The closest equivalent is a range based for-loop. For example,

auto y = {0, 1, 2, 3, 4, 5, 6};

for (auto i : y)
{
  // do something with i
}

There are more details, but these depend on what you want to do. The C++ semantics are quite different to python's.

Sign up to request clarification or add additional context in comments.

1 Comment

@SethMMorton Yes, both the use of auto and the range based for-loop are C++11.
0

In C++ you can use std::for_each which can be answer for you question. More information you can find here.

Comments

0

The for i in range(5) loop would "look" for i in the [0, 1, 2, 3, 4], so it would be quite similar in working as a C++ for (int i = 0; i < 5; ++i).

3 Comments

I don't think that matters. There was a question on understanding how to use the for loop in python, the example I have used is clearer to get I think, as the y would be a collection, wouldn't it?
Of course it matters, because the C++ loop you show is only equivalent to the python loop if you have a sequence of integers 0, 1, 2, ...
This is why I have used the above example. Quick thought: @user2803490 gets the C/C++ loop, so my example might help him understand the idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.