c++中vector二维数组遍历
时间: 2025-04-29 20:49:05 浏览: 30
### C++ 中遍历二维 `vector` 数组的方法
在 C++ 中,可以使用多种方法来遍历二维 `vector<int>`。以下是几种常见的遍历方式:
#### 使用嵌套循环遍历
最直观的方式是通过两个嵌套的 `for` 循环来进行遍历。外层循环用于迭代每一行,而内层循环则负责处理每行中的各个元素。
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (size_t i = 0; i < matrix.size(); ++i) {
for (size_t j = 0; j < matrix[i].size(); ++j) {
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
```
这种方法简单明了,适用于大多数场景[^1]。
#### 使用范围基 `for` 循环
自 C++11 起引入了更简洁的语法——范围基 `for` 循环。这种方式不仅使代码更加易读,而且减少了潜在错误的发生几率。
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (const auto& row : matrix) {
for (const int element : row) {
std::cout << element << " ";
}
std::cout << "\n";
}
return 0;
}
```
此方法利用现代 C++ 的特性简化了传统索引访问模式,在保持功能不变的同时提高了可维护性和清晰度。
#### 迭代器遍历
对于需要更多灵活性的情况,还可以采用迭代器的方式来实现遍历操作。这允许程序以统一接口处理不同类型的容器对象。
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (auto it_row = matrix.begin(); it_row != matrix.end(); ++it_row) {
for (auto it_col = (*it_row).begin(); it_col != (*it_row).end(); ++it_col) {
std::cout << *it_col << " ";
}
std::cout << "\n";
}
return 0;
}
```
尽管这种写法相对复杂一些,但在某些特定场合下却能提供更大的便利性。
阅读全文
相关推荐


















