简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM