输出为 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::list
、std::map
等等。它们适用于任意迭代器值范围。
关于c++ - 为什么这些基于范围的 for 循环不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14595558/