• C++ 中迭代器的使用


    在C++中,"iter"通常是一个缩写,代表迭代器(iterator),用于遍历容器类(如数组、列表、向量等)中的元素。迭代器允许你按顺序访问容器中的元素,而无需了解底层容器的实现细节。以下是关于如何使用C++迭代器的一些基本示例:

    1. 使用迭代器遍历数组:

    #include 
    #include 
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
    
        // 使用迭代器遍历向量
        std::vector<int>::iterator it;
        for (it = numbers.begin(); it != numbers.end(); ++it) {
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在上面的示例中,我们使用std::vector::iterator来声明一个迭代器,然后使用begin()end()成员函数来获取容器的开始和结束迭代器。然后,我们使用迭代器来遍历容器并打印出元素的值。

    2. 使用auto简化迭代器声明:

    C++11引入了auto关键字,可以更简便地声明迭代器:

    #include 
    #include 
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
    
        // 使用auto声明迭代器
        for (auto it = numbers.begin(); it != numbers.end(); ++it) {
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3. 使用范围循环(Range-Based Loop):

    C++11还引入了范围循环,它可以更加简洁地遍历容器中的元素:

    #include 
    #include 
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
    
        // 使用范围循环
        for (const auto& num : numbers) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    范围循环自动选择合适的迭代器类型,并提供了更简单的语法。

    迭代器是C++中用于访问容器元素的重要工具,使你能够以一种通用的方式遍历不同类型的容器。在实际编程中,你可以根据需要选择使用不同类型的迭代器,以便更好地管理容器中的数据。

  • 相关阅读:
    SpringCloud整合Nacos
    ORM 单表记录与字段操作
    本地客户端连接阿里云Redis服务器
    向NS-3添加新模块_ns3.35添加新模块_ns3.35以及更早版本添加新模块
    @Autowired和@Resource的区别
    hadoop 2.0 MapReduce全方面了解
    Linux cp命令:复制文件和目录
    代码规范HelloWorld
    线程——进程与线程——day10
    PHP GET,POST请求file_get_contents拼接header
  • 原文地址:https://blog.csdn.net/qq_42244167/article/details/133932794