Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between for each ( in ) and for ( : )?

Tags:

As someone who has a background in python, I was quite surprised when I first saw the for ( : ) loop:

vector<int> vec = {1,2,3,4}; int sum = 0; for (int i : vec){     sum += i; } //sum is now 10 

This is a very useful construct and should probably be used whenever you don't need the index of a value multiple times.

But today I found there also is a for each ( in ) loop, used like this:

vector<int> vec = {1,2,3,4}; int sum = 0; for each (int i in vec){     sum += i; } //sum is now 10 

Interestingly, google results for the second one are mostly related to Microsoft, not the usual c++ reference websites.

What are the differences between these two loops?

like image 272
iFreilicht Avatar asked Apr 03 '14 11:04

iFreilicht


People also ask

What is the difference between for in and for of?

The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object.

What is the difference between foreach and each?

each differs for the arguments passed to the callback. If you use _. forEach , the first argument passed to the callback is the value, not the key. So if you don't bother at all about the key you should use _.

What is difference between for and foreach in Java?

The for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.


2 Answers

The first is called a range-based for loop and is a C++11 feature of the language. It allows you to iterate like that over ranges that have a begin() and end() method available (member or non-member) or are arrays.

The second is a Microsoft specific syntax, available for C++/CLI but also made available to C++. It allows to iterate through an array or collection. Its use is not recommended and the range-based for loop should be preferred. See for each, in.

like image 75
Marius Bancila Avatar answered Sep 28 '22 02:09

Marius Bancila


The for each loop is provided by Microsoft Visual C++. See: http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx

It is not standard C++ and is quite old (introduced in VS2005). The compiler (VS) converts this loop to proper for loops on compile.

So it is best to stick with regular for ( ; ; ) loops or the for ( : ) loop to allow compatibility with other compiles such as g++.

like image 23
Mo Beigi Avatar answered Sep 28 '22 02:09

Mo Beigi