How can we traverse the elements in a vector in C++?

The easiest way to iterate through elements in a vector in C++ is by using a range-based for loop. Here is an example:

#include <iostream>
#include <vector>

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

    // 使用范围循环遍历vector中的元素
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

The code above will output the following content:

1 2 3 4 5

In addition to using range-based for loops, you can also use iterators to traverse the elements in a vector. Here is an example of using iterators:

#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 << " ";
    }
    std::cout << std::endl;

    return 0;
}

This code will also output the following content:

1 2 3 4 5

Both range loops and iterators can easily traverse the elements in a vector.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds