如何遍历std::vector<std::string>
时间: 2024-05-02 12:14:55 浏览: 276
C++ Vector遍历的几种方式
遍历std::vector<std::string>的方法有很多种,这里给出两种常见的方法:
方法一:使用下标遍历
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> vec = {"hello", "world", "example"};
for (size_t i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << std::endl;
}
return 0;
}
```
方法二:使用迭代器遍历
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> vec = {"hello", "world", "example"};
for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
```
阅读全文