我想在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到相同的一个,它引发了错误。我测试了一下,看看我是否可以为两个不同的变量堆栈模板,但这是不可能的。
我该如何让函数获取任意大小的二维数组并且不会导致该错误?
哎呀对不起生病更新的代码。那是我测试如果我可以通过第二个模板变量。 –