我问c++语言vector的遍历
时间: 2023-07-21 22:59:39 浏览: 55
在C++语言中,可以使用迭代器或范围-based for循环来遍历vector。以下是两种常见的遍历方式:
1. 使用迭代器:
```cpp
#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;
}
```
2. 使用范围-based for循环(C++11及以上版本):
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用范围-based for循环遍历
for (const auto& element : vec) {
std::cout << element << " ";
}
return 0;
}
```
这两种方式都可以遍历vector中的元素并输出它们。你可以根据实际需求选择适合的遍历方式。
相关问题
C++中vector遍历
在C++中,vector是一种动态数组,可以存储不同类型的元素。遍历vector可以使用循环结构,如for循环或者范围-based for循环。
以下是两种常见的vector遍历方式:
1. 使用for循环:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用for循环遍历vector
for (int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << " ";
}
return 0;
}
```
2. 使用范围-based for循环(C++11及以上版本支持):
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用范围-based for循环遍历vector
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
```
这两种方式都可以遍历vector中的元素,并输出它们的值。需要注意的是,使用for循环时,需要使用vec.size()来获取vector的大小作为循环条件。
c++:vector遍历
vector可以通过迭代器进行遍历,具体方式如下:
```c++
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 通过迭代器遍历
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 使用范围for循环遍历
for (auto i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
```
输出:
```
1 2 3 4 5
1 2 3 4 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)