为什么这些基于范围的 for 循环不能正常工作?

Why don't these range based for loops work properly?

本文关键字:不能 循环 常工作 工作 for 于范围 为什么 范围      更新时间:2023-10-16

输出为 2 3 4 5 2293456 6 10 1355995651 12980632 0

看来我没有正确递增

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int x[5] = {1,2,3,4,5};
    vector<int> vec = {2, 4, 6, 8, 10};
    for(int i : x) {
        cout<<x[i]<<endl;
    }
    cout<<endl;
    for(int i : vec) {
        cout<<vec[i]<<endl;
    }
}

使用基于范围的 for 循环时,获取的是容器中的,而不是容器中的索引。因此i是数组/向量内部的值,而不是索引。

请记住:基于范围的 for 循环适用于没有索引的容器,如 std::liststd::map 等。它们处理任意迭代器的值范围。