我想在C++中編寫一個函數,它將採用2個輸入std :: arrays,並通過矩陣乘法返回一個產品數組。然而,該功能不能拿不同尺寸的數組(前四輪驅動的作品,3x4的沒有)
傳遞2d std :: array來函數cpp
這裏是代碼:
#include <iostream>
#include <array>
template <std::size_t SIZE>
void dot(std::array<std::array<double, SIZE>, SIZE>& array1,
std::array<std::array<double, SIZE>, SIZE>& array2)
{
int x1 = array1.size();
int y1 = array1[0].size();
int x2 = array2.size();
int y2 = array2[0].size();
}
int main()
{
using std::array;
array<array<double, 4>, 4> syn0 = {{ {1,2,4},
{2,3,4},
{6,8,6},
{1,2,4} }};
dot(syn0, syn0);
return 0;
}
使用模板例如在本question提出,它將接受像代碼中那樣的4x4等數組。
更改矩陣數目不等的產生如下錯誤:
newer.cpp: In function ‘int main()’:
newer.cpp:23:21: error: too many initializers for ‘std::__array_traits<std::array<double, 4ul>, 3ul>::_Type {aka std::array<double, 4ul> [3]}’
{1,2,4} }};
^
newer.cpp:24:17: error: no matching function for call to ‘dot(std::array<std::array<double, 4ul>, 3ul>&, std::array<std::array<double, 4ul>, 3ul>&)’
dot(syn0, syn0);
^
newer.cpp:24:17: note: candidate is:
newer.cpp:6:6: note: template<long unsigned int SIZE> void dot(std::array<std::array<double, SIZE>, SIZE>&, std::array<std::array<double, SIZE>, SIZE>&)
void dot(std::array<std::array<double, SIZE>, SIZE>& array1,
^
newer.cpp:6:6: note: template argument deduction/substitution failed:
newer.cpp:24:17: note: deduced conflicting values for non-type parameter ‘SIZE’ (‘4ul’ and ‘3ul’)
dot(syn0, syn0);
^
newer.cpp:24:17: note: ‘std::array<std::array<double, 4ul>, 3ul>’ is not derived from ‘std::array<std::array<double, SIZE>, SIZE>
我假定這樣做的原因是,該模板只分配一個變量,所以,如果我分配2到相同的一個,它引發了錯誤。我測試了一下,看看我是否可以爲兩個不同的變量堆棧模板,但這是不可能的。
我該如何讓函數獲取任意大小的二維數組並且不會導致該錯誤?
哎呀對不起生病更新的代碼。那是我測試如果我可以通過第二個模板變量。 –