[英]Why does foreach in C++ can't traverse the first element?
In foreach
loop, it seems the first element is not traversed and the 6th element num[5]
is traversed which is undefined.在
foreach
循环中,似乎第一个元素没有被遍历,而第 6 个元素num[5]
被遍历,这是未定义的。
#include<iostream>
using namespace std;
int num[5];
int main() {
for (int i = 0; i < 5; i++) num[i] = i + 1;
for (auto i : num) cout << num[i] << " ";
return 0;
}
expected output: 1,2,3,4,5预计 output:1,2,3,4,5
output: 2,3,4,5,0 output:2,3,4,5,0
Because i
is not an index, but the value, you should replace:因为
i
不是索引,而是值,所以您应该替换:
for (auto i:num)cout<<num[i]<<" ";
with和
for (auto i:num)cout<< i <<" ";
Then you get the proper output 1 2 3 4 5
然后你得到正确的 output
1 2 3 4 5
for (int i=0;i<5;i++)num[i]=i+1;
Loads the num
variable like [0] = 1
, [1] = 2
... [4] = 5
加载
num
变量,如[0] = 1
, [1] = 2
... [4] = 5
for (auto i:num)cout<<num[i]<<" ";
This actually goes through the values in num
, not the indexes, so what you have here is printing num[1]
, num[2]
... num[5]
( num[5]
is undefined behavior by the way)这实际上是通过
num
中的值,而不是索引,所以你在这里打印的是num[1]
, num[2]
... num[5]
(顺便说一下, num[5]
是未定义的行为)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.