一般形式:
for( decl : coll)
{
Statement;
}
可以将vector vec中的各个元素乘3。
std::vector<double> vec;
...
for ( auto& elem : vec )
{
elem *= 3;
}
以下两种情况表示的是同一种操作:
for ( decl : coll )
{
//statement
}
for (auto _pos=coll.begin(), _end=coll.end(); _pos!=_end; ++_pos )
{
decl = *_pos;
Statement
}
//如果不满足上面的那种,那么便可以用下面的形式表示:
for (auto _pos=begin(coll), _end=end(coll); _pos!=_end; ++_pos )
{
decl = *_pos;
statement
}
而且你也可以使用寻常的固定大小的C风格数组:
int array[] = { 1, 2, 3, 4, 5 };
long sum=0; // process sum of all elements
for (int x : array)
{
sum += x;
}
for (auto elem : { sum, sum*2, sum*4 } )
{
std::cout << elem << std::endl;
}
//输出:15,30,60
但是当构造函数被explicit修饰的时候,下面这样就不被允许:
class C
{
public:
explicit C(const std::string& s){...}; // explicit(!) type conversion from strings
};
...
std::vector<std::string> vs;
for (const C& elem : vs) // ERROR, no conversion from string to C defined
{
...
}