gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:36:53 29 4
gpt4 key购买 nike

输出为 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 是数组/vector 内部的值,而不是索引。

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

关于c++ - 为什么这些基于范围的 for 循环不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14595558/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com