基于范围的 for 语句 (C++)

本文通过示例详细介绍了C++中范围for循环的使用方法,包括不同类型的迭代变量(值、引用等)如何影响数组及vector容器的遍历过程,并对比了不同声明方式的特点。
// range-based-for.cpp
// compile by using: cl /EHsc /nologo /W4
#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    // Basic 10-element integer array.
    int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Range-based for loop to iterate through the array.
    for( int y : x ) { // Access by value using a copy declared as a specific type. 
                       // Not preferred.
        cout << y << " ";
    }
    cout << endl;

    // The auto keyword causes type inference to be used. Preferred.

    for( auto y : x ) { // Copy of 'x', almost always undesirable
        cout << y << " ";
    }
    cout << endl;

    for( auto &y : x ) { // Type inference by reference.
        // Observes and/or modifies in-place. Preferred when modify is needed.
        cout << y << " ";
    }
    cout << endl;

    for( const auto &y : x ) { // Type inference by reference.
        // Observes in-place. Preferred when no modify is needed.
        cout << y << " ";
    }
    cout << endl;
    cout << "end of integer array test" << endl;
    cout << endl;

    // Create a vector object that contains 10 elements.
    vector<double> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(i + 0.14159);
    }

    // Range-based for loop to iterate through the vector, observing in-place.
    for( const auto &j : v ) {
        cout << j << " ";
    }
    cout << endl;
    cout << "end of vector test" << endl;
}

输出如下:

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

end of integer array test

0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159

end of vector test

C++ 中,`for` 循环是一种常用的控制结构,用于重复执行一段代码。它提供了多种使用方式,从传统的基于计数器的循环到现代的范围基础循环。以下是对 `for` 循环的详细用法及示例说明。 ### 传统 `for` 循环 传统 `for` 循环的语法如下: ```cpp for (初始化; 条件; 更新) { // 循环体 } ``` - **初始化**:通常用于声明和初始化循环变量。 - **条件**:在每次循环迭代之前检查条件,如果为真,则执行循环体。 - **更新**:通常用于更新循环变量。 #### 示例 ```cpp for (int i = 0; i < 5; ++i) { std::cout << "Iteration " << i << std::endl; } ``` ### 基于范围的 `for` 循环(C++11 及以后) C++11 引入了基于范围的 `for` 循环,使得遍历容器或数组更加简洁。 ```cpp for (元素类型 元素 : 容器或数组) { // 循环体 } ``` #### 示例 ```cpp std::vector<int> vec = {1, 2, 3, 4, 5}; for (int num : vec) { std::cout << num << std::endl; } ``` ### 使用迭代器的 `for` 循环 在处理 STL 容器时,可以使用迭代器来遍历元素。 #### 示例 ```cpp std::vector<int> vec = {1, 2, 3, 4, 5}; for (auto it = vec.begin(); it != vec.end(); ++it) { std::cout << *it << std::endl; } ``` ### 使用 `std::for_each` 的 `for` 循环 `std::for_each` 是 STL 提供的一个算法,可以用于对容器中的每个元素执行操作。 #### 示例 ```cpp #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::for_each(vec.begin(), vec.end(), [](int num) { std::cout << num << std::endl; }); return 0; } ``` ### 使用 `foreach` 宏(Visual Studio 扩展) 某些编译器(如 Visual Studio)提供了非标准的 `foreach` 宏来简化遍历。 #### 示例 ```cpp #include <afx.h> // MFC 核心头文件 #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; CString strText; foreach (int item in vec) { strText.Format("%d", item); AfxMessageBox(strText); } return 0; } ``` ### 注意事项 - **避免过度使用技巧**:虽然 `for` 循环的灵活性很高,但过度使用技巧可能导致代码难以理解和维护。例如,空缺初始化语句和条件表达式可能会使代码变得复杂[^1]。 - **变量作用域**:在 `for` 循环中声明的变量仅在循环体内可见。如果在循环外声明变量,可以在循环内重新声明同名变量,但这可能会引起混淆,应尽量避免[^2]。 ### 总结 C++ 提供了多种 `for` 循环的用法,适用于不同的场景。从传统的基于计数器的循环到现代的基于范围的循环,每种方式都有其适用的场合。选择合适的循环方式可以提高代码的可读性和可维护性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值