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?
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.
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 _.
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.
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.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With