基于范围的for循环的奇怪问题
Weird issue with range based for loop
我正在我的 C++ 面向对象 1 class 中学习向量,我们已经介绍了基于范围的 for 循环的概念。我决定单独练习基于范围的 for 循环,以便我可以习惯语法,但我遇到了一个奇怪的问题。
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
for ( auto i: a)
{
cout << a[i] << " ";
}
return 0;
}
当我运行上面的代码时,我的输出如下。
2 3 4 5 6 7 8 9 0 1 Press any key to continue...
我的输出应该是
1 2 3 4 5 6 7 8 9 0 Press any key to continue...
谁能告诉我为什么我的第一个索引被跳过了?我有 visual studio 2013 专业。
你会得到奇怪的输出,因为范围循环中的 i
是数组中的值,而不是索引。即,
for (auto i : a)
循环遍历 a
的 值 。在您的代码中,您有效地打印了序列 a[a[0]]
、a[a[1]]
等
您可能需要的代码是
for (auto i : a) {
std::cout << i << std::endl;
}
我正在我的 C++ 面向对象 1 class 中学习向量,我们已经介绍了基于范围的 for 循环的概念。我决定单独练习基于范围的 for 循环,以便我可以习惯语法,但我遇到了一个奇怪的问题。
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
for ( auto i: a)
{
cout << a[i] << " ";
}
return 0;
}
当我运行上面的代码时,我的输出如下。
2 3 4 5 6 7 8 9 0 1 Press any key to continue...
我的输出应该是
1 2 3 4 5 6 7 8 9 0 Press any key to continue...
谁能告诉我为什么我的第一个索引被跳过了?我有 visual studio 2013 专业。
你会得到奇怪的输出,因为范围循环中的 i
是数组中的值,而不是索引。即,
for (auto i : a)
循环遍历 a
的 值 。在您的代码中,您有效地打印了序列 a[a[0]]
、a[a[1]]
等
您可能需要的代码是
for (auto i : a) {
std::cout << i << std::endl;
}