在C++中,可以使用嵌套循環(huán)來(lái)實(shí)現(xiàn)矩陣乘法。以下是一個(gè)示例代碼:
#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;
}
在這個(gè)示例中,我們首先定義了一個(gè)函數(shù)matrixMultiply
,該函數(shù)接受兩個(gè)矩陣作為參數(shù),并返回它們的乘積矩陣。然后在main
函數(shù)中創(chuàng)建兩個(gè)矩陣mat1
和mat2
,調(diào)用matrixMultiply
函數(shù)進(jìn)行矩陣乘法運(yùn)算,并打印結(jié)果。