简体   繁体   English

for(x:y)循环在c ++中无法正常工作

[英]for (x:y) loop isnt working properly in c++

I've tried 2 different for loops, 1 of which works but the other doesn't appear to. 我尝试了2种不同的for循环,其中一种有效,但其他似乎没有。 output of the first for loop: 2 3 4 5 5, output of the second for loop: 1 2 3 4 5. 第一个for循环的输出:2 3 4 5 5,第二个for循环的输出:1 2 3 4 5。

#include <iostream>
int main() 
{
    int arr[5] = {1,2,3,4,5};
    for (int y : arr) std::cout << arr[y] << std::endl;
    std::cout << "---------" << std::endl;
    for (int i = 0; i<5;i++){
        std::cout << arr[i] << std::endl;
    }
    return 0;
}

The first loop is a range-based loop, used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container ( https://en.cppreference.com/w/cpp/language/range-for ) 第一个循环是基于范围的循环,与在范围内的值(例如容器中的所有元素,例如https://en.cppreference.com/w/cpp/语言/范围

It is similar to a java or C# foreach style loop. 它类似于Java或C# foreach样式循环。

In this kind of loop, the values that y takes are the values of the elements in the array themselves ( 1,2,3,4,5), not the indexes (0,1,2...) so you don't need to print arr[y] , just print y itself 在这种循环中,y取的值是数组本身中的元素的值(1,2,3,4,5),而不是索引(0,1,2 ...),因此您不必不需要打印arr[y] ,只打印y本身

For example, both the loops in the following code will print 10,20,30,40,50 例如,以下代码中的两个循环将打印10,20,30,40,50

#include <iostream>
int main() 
{
    int arr[5] = {10,20,30,40,50};
    for (int y : arr) std::cout << y << std::endl;
    std::cout << "---------" << std::endl;
    for (int i = 0; i<5;i++){
        std::cout << arr[i] << std::endl;
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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