阅读量:0
在C++中,可以使用嵌套循环来实现矩阵乘法。以下是一个示例代码:
#include <iostream> #include <vector> using namespace std; vector<vector<int>> matrixMultiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) { int rows1 = mat1.size(); int cols1 = mat1[0].size(); int cols2 = mat2[0].size(); vector<vector<int>> result(rows1, vector<int>(cols2, 0)); for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols2; j++) { for (int k = 0; k < cols1; k++) { result[i][j] += mat1[i][k] * mat2[k][j]; } } } return result; } int main() { vector<vector<int>> mat1 = {{1, 2, 3}, {4, 5, 6}}; vector<vector<int>> mat2 = {{7, 8}, {9, 10}, {11, 12}}; vector<vector<int>> result = matrixMultiply(mat1, mat2); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[0].size(); j++) { cout << result[i][j] << " "; } cout << endl; } return 0; }
在这个示例中,我们首先定义了一个函数matrixMultiply
,该函数接受两个矩阵作为参数,并返回它们的乘积矩阵。然后在main
函数中创建两个矩阵mat1
和mat2
,调用matrixMultiply
函数进行矩阵乘法运算,并打印结果。