溫馨提示×

C++ Vector容器怎樣遍歷

c++
小樊
213
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女