为了简化for语句的操作,c++引入了一个更加简单的for语句操作-**范围for语句**。

常规的for语句:

for(initializer; condition; cxpression)
    statement
//eg:
for(auto i = 0; i < n; i++)
    cout<<i<<endl;

范围for语句:

for(declaration : expression)
    statement
//eg:
vector<int> v = {0, 1, 2, 3, 4, 5}
for(auto &r : v)
    r *= 2; 

此处的 auto &r 必须是引用类型,才能对元素进行写操作,因为上面的语句等价于:

for(auto beg = v.begin(), end = v.end(); beg != end; ++beg)
{
    auto &r = *beg;
    r *= 2
}

参考书籍:C++Primer第五版