5. 范围 for 语句

范围 for 语句 是 C++11 版本后推出的一种语句,它用于遍历容器、数组或任何可迭代序列中的每个元素。它语法简洁非常容易使用。

范围 for 语句 可以用于遍历任何含有 begin()end()成员函数并返回迭代器的可迭代的对象。

语法

for (类型 变量: 可迭代对象) {
   ... 循环体.
}

例如

for (int x: myarr) {
   ...
}
// 等同于:
for (auto it = myarr.begin(); it != myarr.end(); ++it) {
    int x = *it;
    ...
}

范围 for 语句不但可以用于遍历 STL 中的容器,还可以用于遍历数组。

示例

// filename: range_for.cpp
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v = {11, 3, 7, 5, 9};
    // 遍历容器对象
    for (int value : v) {
        cout << "value: " << value << endl;
    }

    // 遍历原生数组
    int arr1[] = {111, 222, 333, 444};
    for (int value: arr1) {
        cout << "value:" << value << endl;
    }

    return 0;
}

编译和运行结果如下

weimz@mzstudio:~$ g++ -o range_for range_for.cpp
weimz@mzstudio:~$ ./range_for 
value: 11
value: 3
value: 7
value: 5
value: 9
value:111
value:222
value:333
value:444