当前位置:首页 C++ > 正文

c++STL模板中遍历向量的几种方法

作者:野牛程序员:2023-09-14 09:46:24 C++阅读 2738

在C++98语法中,可以使用不同的方法来遍历STL向量。以下是几种常用的遍历方法:

  1. 使用普通for循环: 使用传统的for循环可以遍历向量,并使用迭代器或下标访问元素。

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
            std::cout << *it << " ";
        }
    
        return 0;
    }

    或者,使用下标来访问元素:

    for (std::vector<int>::size_type i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
  2. 使用迭代器范围: 可以使用迭代器范围进行遍历,这在C++98中是一种更现代的做法。

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
            std::cout << *it << " ";
        }
    
        return 0;
    }
  3. 使用STL算法和函数指针: 可以使用STL算法(如for_each)结合函数指针或函数对象来遍历向量。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    // 函数对象
    struct PrintElement {
        void operator()(int element) const {
            std::cout << element << " ";
        }
    };
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        // 使用for_each和函数对象
        std::for_each(vec.begin(), vec.end(), PrintElement());
    
        return 0;
    }
  4. 使用范围-based for 循环(C++11之后才支持): 如果编译环境支持C++11或更高版本,可以使用范围-based for 循环来更简洁地遍历向量。

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        for (int element : vec) {
            std::cout << element << " ";
        }
    
        return 0;
    }

请注意,在C++98中,没有范围-based for 循环,因此需要使用传统的for循环或STL算法来遍历向量。但如果编译环境支持C++11或更高版本,使用范围-based for 循环是更简洁和方便的方法。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击