我正在尝试使用清晰的函数对随机生成的值进行矩阵乘法。因此,我希望使用一个函数 (mat_def
) 生成矩阵,并在将矩阵作为参数发送时使用另一个函数 (mat_mul
) 将它们相乘。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
double mat_def(int n) //how to return the matrix
{
double a[n][n];
double f;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
f= rand();
cout<<f ;
a[i][j]=f;
}
}
return 0;
}
double mat_mul( int n, double a[n][n], double b[n][n]) //how to send matrix as parameter
{
return 0;
}
int main()
{
/* initialize random seed: */
srand (time(NULL));
mat_def(10);
}
最佳答案
这里有一个漂亮的标准 C++ 矩阵模板。
矩阵.h
#include <vector>
class Matrix
{
class InnerM
{
private:
int ydim;
double* values;
public:
InnerM(int y) : ydim(y)
{
values = new double[y];
}
double& operator[](int y)
{
return values[y];
}
};
private:
int xdim;
int ydim;
std::vector<InnerM> inner;
public:
Matrix(int x, int y) : xdim(x), ydim(y), inner(xdim, InnerM(ydim))
{
}
InnerM& operator[](int x)
{
return inner[x];
}
};
所有的内存泄漏都是为你准备的,但你明白了。在这里,您可以通过覆盖 Matrix 类中的 ::operator*()
来处理乘法。
关于c++ - 矩阵 - 返回并作为参数传递 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44550155/