4/26打卡,范围for循环

范围for循环的语法形式为for (declaration : range),其中declaration是一个声明语句,用于定义一个变量,range是一个表达式,表示要遍历的范围。

在每次循环迭代中,范围for循环会从range中取出一个元素,并用它来初始化declaration中定义的变量。然后执行循环体中的语句。当range中的所有元素都被遍历完后,循环就结束了。

范围for循环可以用来遍历任何支持迭代器的容器,比如vector、list、set、map等。它也可以用来遍历数组。下面是一些使用范围for循环的例子:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // 遍历vector
    vector<int> v = {1, 2, 3, 4, 5};
    for (int x : v) {
        cout << x << ' ';
    }
    cout << endl;

    // 遍历数组
    int a[] = {1, 2, 3, 4, 5};
    for (int x : a) {
        cout << x << ' ';
    }
    cout << endl;

    // 遍历字符串
    string s = "hello";
    for (char c : s) {
        cout << c << ' ';
    }
    cout << endl;

    return 0;
}

 

posted @ 2023-04-27 20:42  aallofitisst  阅读(30)  评论(0)    收藏  举报