可以使用 for 循环或者迭代器来遍历 vector

使用 for 循环遍历:

#include <vector>
#include <string>
#include <iostream>

int main() {
    std::vector<std::string> vec = {"hello", "world", "!"};
    for (int i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

使用迭代器遍历:

#include <vector>
#include <string>
#include <iostream>

int main() {
    std::vector<std::string> vec = {"hello", "world", "!"};
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    return 0;
}

其中,auto 关键字可以自动推导出迭代器类型

c++ 实现 循环遍历 vector string

原文地址: http://www.cveoy.top/t/topic/eP5m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录