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;
}
から
コール?
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スタイルです。ベクトルのベクトルを使用する(インデックス作成は依然として非常に効率的です)。
size_t rows(5);
size_t columns(15);
vector<float> row(columns);
vector<vector<float>> matrix(rows, row);
matrix[0][0] = 0.1f;
いっそのように、必要な行列演算を実装保持および寸法を適用し、行列乗算のために互換性が保証され、マトリックスクラスの基礎となるストレージを包みます。
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のようなライブラリを検討対独自のロールでした。これはテンプレート化されたコードで、スパース、斜め、その他の一般的なタイプのマトリックスの特殊化をサポートします。
どのようなタイプの2D配列(実際にはD1×D2)配列への参照を渡すことで、このようになります。これにより、何かを返す必要もなくなります。
関数が入力配列の引数を変更する必要がある場合は、constを削除します。
void f(T const (&r)[D1][D2]){}
int main() {
float fbuf[10][3];
f(fbuf);
}
あなたはしかし、関数は2次元配列を返したことを主張した場合、あなたはそのような何かがあります。
template<class T, size_t D1, size_t D2>
T (&f(T const (&r)[D1][D2]))[D1][D2]{
T temp[D1][D2];
return temp;
}
int main() {
float fbuf[10][3];
f(fbuf);
}
をあなたが書いていることは、C++コードは有効ではありません。 result
を適切なサイズに初期化するには、row
とcol
がコンパイル時定数である必要があります。ローカルに割り当てる関数からfloat**
を返すか、関数に別のパラメータとして事前割り当てされたfloat** result
を渡します(それでも返すことができます)。しかし、通常は行列を格納するために2次元配列を使用しませんが、1次元配列の行列の線形記憶域を定義し、適切なアクセサを定義することになります。
float** matrix__multiplication(float **arrayA,float **arrayB,float **result, int row1,int col1,int col2)
{
// ...
return result;
}
// caller needs to allocate (and de-allocate) space (see the mess?):
result = new float* [row1];
std::for_each(result, result + row1, [col2] (float*& pCurr) -> void {
pCurr = new float[col2];
});
result = matrix_multiplication(a, b, result, row1, col1, col2);
'type arr [] []'と 'type ** arr'には大きな違いがあります。 1つを選択します。また、 'result'はスタック変数であり、関数を終了してももう存在しないことに注意してください! – ruslik
おそらくstd :: vectorを使用すると、人生が楽になるでしょう。http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027 – nabulke