vector创建二维动态数组
时间: 2023-05-29 11:03:52 浏览: 77
以下是使用vector创建二维动态数组的示例代码:
```
#include <vector>
#include <iostream>
int main() {
int rows = 3;
int cols = 4;
std::vector<std::vector<int>> arr(rows, std::vector<int>(cols));
// 初始化数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = i * cols + j;
}
}
// 打印数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了二维数组的行数和列数,然后使用vector创建了一个二维动态数组。创建方式是先定义一个vector,然后指定其元素类型为vector<int>,即每个元素是一个int类型的vector。接着使用vector的构造函数初始化数组的行数和列数。
然后我们使用两层for循环初始化数组的值,最后再使用两层for循环打印数组的值。注意,在使用vector创建二维数组时,不能像静态数组那样使用arr[i][j]的方式访问元素,而需要使用arr.at(i).at(j)的方式访问。