c++怎么遍历vector数组

   2025-02-13 6630
核心提示:C++中可以使用循环来遍历vector数组。以下是两种常见的遍历方式:使用for循环遍历vector数组:#include iostream#include vector

C++中可以使用循环来遍历vector数组。以下是两种常见的遍历方式:

使用for循环遍历vector数组:
#include <iostream>#include <vector>int main() {    std::vector<int> vec = {1, 2, 3, 4, 5};    // 使用for循环遍历vector数组    for (int i = 0; i < vec.size(); i++) {        std::cout << vec[i] << " ";    }    return 0;}
使用迭代器遍历vector数组:
#include <iostream>#include <vector>int main() {    std::vector<int> vec = {1, 2, 3, 4, 5};    // 使用迭代器遍历vector数组    for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {        std::cout << *it << " ";    }    return 0;}

无论是使用for循环还是使用迭代器,都可以依次访问vector数组中的每个元素。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言