C++11为我们提供了更为简便的for语句,可以遍历容器或者其他序列.
语法形式:
for (declaration : expression)
{
statement
}
代码示例:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// 遍历数组
int a[] = {1,2,3,4,5};
for (auto x: a)
{
cout << x << " " ;
}
cout << endl;
// 遍历并修改vector,将其中每一个元素乘以2
// Note1:要对序列进行修改,声明的变量必须为引用.
// Note2:不能在for范围内对vector或者其他对象增加或删除元素,
// 否则可能会导致for范围end()无效.
vector<int> v = {1,2,3,4,5};
for (auto &e : v)
{
e *= 2;
}
for (auto &e: v)
{
cout << e << " ";
}
cout << endl;
return 0;
}