[英]Passing 2d std::array to function cpp
I am trying to write a function in c++ that will take 2 input std::arrays, and return an array of the products via matrix multiplication. 我试图在c ++中编写一个函数,它将采用2个输入std :: arrays,并通过矩阵乘法返回一个产品数组。 However, the function cannot take an array with different dimensions (ex. 4x4 works, 3x4 does not)
但是,该函数不能采用不同尺寸的数组(例如4x4工作,3x4不工作)
here is the code: 这是代码:
#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;
}
Using the template example as posed in this question , it will accept arrays such as 4x4 like in the code. 使用此问题中提出的模板示例,它将接受像代码中的4x4等数组。
Changing the matrix to unequal numbers yields the following errors: 将矩阵更改为不相等的数字会产生以下错误:
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>
I assume the reason for this is that the template only assigns one variable, so if i assign 2 to the same one, it throws the error. 我假设这样做的原因是模板只分配一个变量,所以如果我将2分配给同一个变量,它会抛出错误。 I tested to see if i could stack templates for two different variables, but that is not possible.
我测试了是否可以为两个不同的变量堆叠模板,但这是不可能的。
How can I allow the function to take a 2d array of any size and not cause that error? 如何允许该函数采用任何大小的二维数组而不会导致该错误?
Seems that you were really close. 似乎你真的很亲密。
You just need to add SIZE2
as a parameter to your template: 您只需要将
SIZE2
作为参数添加到模板中:
template <std::size_t SIZE,std::size_t SIZE2>
void dot(std::array<std::array<double, SIZE>, SIZE2>& array1,
std::array<std::array<double, SIZE>, SIZE2>& array2)
and it compiles all right BTW your syn0
size was wrong 它编译好了BTW你的
syn0
大小是错误的
int main()
{
using std::array;
array<array<double, 3>, 4> syn0 = {{ {1,2,4},
{2,3,4},
{6,8,6},
{1,2,4} }};
dot(syn0, syn0);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.