c++

C++ Vector容器怎样遍历

小樊
106
2024-07-30 14:34:11
栏目: 编程语言

在C++中,可以使用以下几种方法来遍历Vector容器:

  1. 使用迭代器遍历:
#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;
}
  1. 使用auto关键字和范围for循环遍历:
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // 使用auto关键字和范围for循环遍历
    for (auto& num : vec) {
        std::cout << num << " ";
    }

    return 0;
}
  1. 使用STL算法中的for_each函数遍历:
#include <iostream>
#include <vector>
#include <algorithm>

void print(int num) {
    std::cout << num << " ";
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // 使用for_each函数遍历
    std::for_each(vec.begin(), vec.end(), print);

    return 0;
}

以上是几种常用的遍历Vector容器的方法,在实际开发中可以根据具体需求选择合适的方式来遍历Vector容器。

0
看了该问题的人还看了