C++ Vector容器怎样遍历

   2024-10-02 5570
核心提示:在C++中,可以使用以下几种方法来遍历Vector容器:使用迭代器遍历:#include iostream#include vectorint main() {std::vectorin

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

使用迭代器遍历:
#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;}
使用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;}
使用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容器。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号