【问题标题】:Passing 2d std::array to function cpp将 2d std::array 传递给函数 cpp
【发布时间】:2016-08-16 21:29:43
【问题描述】:

我正在尝试用 c++ 编写一个函数,该函数将采用 2 个输入 std::arrays,并通过矩阵乘法返回一个乘积数组。但是,该函数不能采用不同维度的数组(例如 4x4 有效,3x4 无效)

这是代码:

#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 分配给同一个变量,则会引发错误。我测试了是否可以为两个不同的变量堆叠模板,但这是不可能的。

我怎样才能让函数采用任意大小的二维数组而不导致该错误?

【问题讨论】:

  • 抱歉,我更新了代码。那是我测试我是否可以传递第二个模板变量。

标签: c++ arrays c++11


【解决方案1】:

看来你们真的很亲近。

您只需将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)

它可以编译 顺便说一句,您的 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;
}

【讨论】:

    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多