温馨提示×

c++使用迭代器遍历数组的方法

c++
小樊
96
2024-07-17 17:18:51
栏目: 编程语言

在C++中,可以使用迭代器来遍历数组。以下是一个示例代码:

#include <iostream>
#include <vector>

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

    // 使用迭代器遍历数组
    for (std::vector<int>::iterator it = arr.begin(); it != arr.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上面的代码中,我们使用std::vector<int>::iterator来声明一个迭代器it,然后通过it来遍历数组arr。在循环中,我们通过*it来访问迭代器指向的元素,并输出到控制台上。

0