在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
函數進行矩陣乘法運算,并打印結果。