从主调用
matrix_multiplication(arrayA,arrayB,row1,col1,col2);
函数定义
float matrix__multiplication(float **arrayA,float **arrayB,int row1,int col1,int col2)
{
float result[row1][col2];
result[][]=....
return result;
}
我想知道如何在函数调用中传递二维数组, 如何在函数定义中接收 以及如何返回结果矩阵?
最佳答案
像这样为数组使用原始指针比 C++ 更符合 C 风格。使用vector of vector(索引还是很高效的)。
size_t rows(5);
size_t columns(15);
vector<float> row(columns);
vector<vector<float>> matrix(rows, row);
matrix[0][0] = 0.1f;
更好的方法是将底层存储包装在 Matrix 类中,该类实现所需的矩阵运算、保持和强制维度、确保矩阵与乘法兼容,等等。
class Matrix
{
public:
Matrix(const int _rows, const int _cols) : rows(_rows), cols(_cols)
{
}
Matrix Multiply(const Matrix& rhs);
private:
vector<vector<float>> storage;
size_t rows;
size_t cols;
};
Matrix Matrix::multiply(const Matrix& rhs)
{
Matrix result(*this, rhs); // construct matrix of right dimensions
// multiply the operands
return result; // modern compilers do not copy construct the result
}
如果您的矩阵需求很复杂,您可以考虑像 Boost.UBlas 这样的库而不是自己动手。这是模板化代码,支持稀疏矩阵、对角矩阵和其他常见矩阵类型的特化。
关于c++ - 如何传递数组并返回二维矩阵的数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4232654/