简体   繁体   English

为什么C++中的foreach不能遍历第一个元素?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM