std::vector 循环
时间: 2023-07-20 10:30:39 浏览: 90
可以使用 for 循环或者迭代器来遍历 std::vector。
使用 for 循环:
```c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
return 0;
}
```
使用迭代器:
```c++
#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;
}
```
使用 range-based for 循环:
```c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (const auto& elem : vec) {
std::cout << elem << " ";
}
return 0;
}
```
阅读全文