阿鑫来了  
//普通for循环
void test(){
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i){
        cout << arr[i] << "  ";
    }
    cout << endl;
}

 

//范围for(更安全,不会越界)     当前的数据 : 循环的范围 
void test1(){
    int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (int e : arr1){
        cout << e << " ";
    }
    cout << endl;
}

 

//可修改的范围for,使用引用,不使用引用无法修改
void test2(){
    int arr2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (int& e : arr2){
        cout << e << " ";
        e = 10;    //全修改为10
    }
    cout << endl;
}

 

推荐使用

//既保证数据不会被修改,效率又高
void test3(){
    int arr3[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (const auto& e : arr3){
        cout << e << " ";
    }
    cout << endl;
}

 

posted on 2021-05-28 20:49  阿鑫来了  阅读(70)  评论(0)    收藏  举报