vector定义二维数组
时间: 2023-09-29 12:08:28 浏览: 83
在C++中,可以通过以下方式定义二维数组:
```
vector<vector<int>> arr; // 定义一个二维数组,元素类型为int
```
然后可以通过以下方式初始化和访问它的元素:
```
// 初始化二维数组
arr = {{1,2,3},{4,5,6},{7,8,9}};
// 访问二维数组元素
int val = arr[1][2]; // 访问第2行第3列的元素
```
相关问题
如何用vector定义二维数组
在C++中,你可以使用`std::vector`来模拟二维数组。这是因为`vector`是一个动态大小的数组容器,可以方便地扩展或收缩其容量。以下是创建一个二维`vector`的基本步骤:
```cpp
#include <iostream>
#include <vector>
int main() {
// 定义二维向量的行数和列数
int rows = 3;
int cols = 4;
// 创建一个二维vector,初始化为空
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));
// 或者直接分配空间并填充元素
// matrix.resize(rows);
// for (int i = 0; i < rows; ++i) {
// matrix[i].resize(cols);
// }
// 访问和修改元素
matrix[0][0] = 1; // 设置第一行第一列的值为1
std::cout << "Matrix(0, 0): " << matrix[0][0] << std::endl;
return 0;
}
```
在这个例子中,`matrix`就是我们所谓的二维`vector`,它内部又是一维`vector`的嵌套结构。访问元素时使用`matrix[row][col]`的方式。
vector定义二维数组并指定大小
你可以使用以下方式定义一个大小为n x m的二维vector数组:
```
vector<vector<int>> arr(n, vector<int>(m));
```
其中n和m分别表示数组的行数和列数。这样定义的二维vector数组中所有元素的默认值都是0。你可以通过双重循环来访问和修改数组中的元素,例如:
```
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
arr[i][j] = i*j;
}
}
```
这段代码将二维数组的每个元素的值设置为其所在行数和列数的乘积。
阅读全文
相关推荐















