簡體   English   中英

將二維數組作為參數傳遞給函數

[英]Passing 2D array into a function as an argument

我正在嘗試將二維數組傳遞給函數。 不幸的是,我堅持使用相當老的編譯器(gcc-4.1)並且無法使用任何現代方法。 經過一些谷歌搜索和堆棧溢出討論。 我想出了這個。 MatrixMN is own implementation of matrices

namespace MatrixMNTest {
//  Test variables

double matrix_4X2[4][2] = {{1, 2}, {3, 4}, {11, 12}, {0, 1}};

template <size_t size1, size_t size2>
MatrixMN getMatrix(const double (&arr)[size1][size2]) {
  MatrixMN m(size1, size2);
  for (unsigned i = 0; i < size1; ++i) {
    for (unsigned j = 0; j < size2; ++j) {
      m(i, j) = arr[i][j];
    }
  }
  return m;
}
}

int main() {

  size_t size1 = 4;
  size_t size2 = 2;
  // success 
  math::MatrixMN A = MatrixMNTest::getMatrix(MatrixMNTest::matrix_4X2);
  double scalar = 2.5;

  double result[size1][size2];
  memcpy(result, MatrixMNTest::matrix_4X2, sizeof(result));
  // fail
  math::MatrixMN B = MatrixMNTest::getMatrix(result);

}

我嘗試在 gcc-4.1 和 7.5.0 上運行相同的代碼來檢查錯誤消息

gcc-4.1

error: no matching function for call to 'getMatrix(double [(((unsigned int)(((int)size1) - 1)) + 1u)][(((unsigned int)(((int)size2) - 1)) + 1u)])'

海灣合作委員會 - 7.5.0

test.cpp: In function ‘int main()’:
test.cpp:96:52: error: no matching function for call to ‘getMatrix(double [size1][size2])’
   math::MatrixMN B = MatrixMNTest::getMatrix(result);
                                                    ^
test.cpp:69:16: note: candidate: template<long unsigned int size1, long unsigned int size2> math::MatrixMN MatrixMNTest::getMatrix(const double (&)[size1][size2])
 math::MatrixMN getMatrix(const double (&arr)[size1][size2]) {
                ^~~~~~~~~
test.cpp:69:16: note:   template argument deduction/substitution failed:
test.cpp:96:52: note:   variable-sized array type ‘long int’ is not a valid template argument
   math::MatrixMN B = MatrixMNTest::getMatrix(result)

不確定..如何解決這個問題。 任何幫助是極大的贊賞。

我將代碼修改為..

const size_t size1 = 4;
const size_t size2 = 2;

double result[size1][size2];

或直接傳遞它們。

double result[4][2];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM