C++ matrix怎样实现动态扩容

avatar
作者
筋斗云
阅读量:0

在C++中,可以使用二维动态数组来实现矩阵,并在需要时进行动态扩容。以下是一个简单的示例代码:

#include <iostream> #include <vector>  using namespace std;  int main() {     // 初始化矩阵大小为3x3     int rows = 3;     int cols = 3;          vector<vector<int>> matrix(rows, vector<int>(cols, 0));          // 输出初始矩阵     for(int i = 0; i < rows; i++) {         for(int j = 0; j < cols; j++) {             cout << matrix[i][j] << " ";         }         cout << endl;     }          // 动态扩容为4x4     rows = 4;     cols = 4;          matrix.resize(rows, vector<int>(cols, 0));          // 输出扩容后的矩阵     for(int i = 0; i < rows; i++) {         for(int j = 0; j < cols; j++) {             cout << matrix[i][j] << " ";         }         cout << endl;     }          return 0; } 

在上面的示例中,我们使用vector<vector<int>>表示矩阵,并使用resize方法在需要时进行动态扩容。当需要扩容时,我们可以直接调用resize方法,并传入新的行和列数即可。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!