使用二维vector可以通过以下步骤:
- 包含 vector 头文件:
#include <vector>
- 声明一个二维vector变量:
std::vector<std::vector<int>> matrix;
- 初始化二维vector的大小:
int numRows = 3;
int numCols = 4;
matrix.resize(numRows, std::vector<int>(numCols));
- 访问和修改二维vector中的元素:
matrix[row][col] = value;
int element = matrix[row][col];
完整示例:
#include <iostream>
#include <vector>
int main() {
int numRows = 3;
int numCols = 4;
std::vector<std::vector<int>> matrix;
matrix.resize(numRows, std::vector<int>(numCols));
// 修改元素值
matrix[0][0] = 1;
matrix[1][1] = 2;
matrix[2][2] = 3;
// 打印二维vector
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
std::cout << matrix[row][col] << " ";
}
std::cout << std::endl;
}
return 0;
}
输出结果:
1 0 0 0
0 2 0 0
0 0 3 0