溫馨提示×

c++怎么遍歷vector數組

小億
282
2023-12-12 11:07:32
欄目: 編程語言

C++中可以使用循環來遍歷vector數組。以下是兩種常見的遍歷方式:

  1. 使用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;
}
  1. 使用迭代器遍歷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數組中的每個元素。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女