【问题标题】:Is it possible to add two multi-dimensional arrays together to a third multi-dimensional array是否可以将两个多维数组一起添加到第三个多维数组
【发布时间】:2014-10-12 00:14:15
【问题描述】:

我试图将两个多维数组一起添加到第三个数组中,但没有成功。我创建的前两个数组有值,我不确定如何将多维数组 a 添加到多维数组 b手在多向数组 c 中有正确的值。下面是我开始提出的。

提前感谢您的时间和技能。

int main()
{
int a[2] [3] = 
{
    { 16, 18, 23 },
    { 54, 91, 11 }
};

int b[2][3] =
{
        { 14, 52, 77 },
        { 16, 19, 59 }
};

int c[2][3];

for (int rows = 0; rows < 2; rows++)
{
    for (int columns = 0; columns < 3; columns++)
    {
        c[rows][columns] = b[rows][columns] + a[rows][columns];
    }
}
_getch();
return 0;

}

【问题讨论】:

  • 您的问题到底是什么?您的代码运行良好,完全符合您的描述。
  • 你是对的。看起来当我第一次将我的 for 循环卡在错误的位置时输出我的代码时,它现在正在工作。我应该删除这个帖子还是留给其他人参考?

标签: c++ arrays multidimensional-array


【解决方案1】:

一种更短的方法:展平指针并使用transform

int c[2][3];
std::transform( *a, *std::end(a), *b, *c, std::plus<int>() ); // Or plus<> since C++14

【讨论】:

  • 感谢您的建议,很高兴知道这一点,而且时间要短得多。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2014-04-10
  • 2011-07-09
  • 2022-01-03
  • 2012-10-18
  • 1970-01-01
  • 2019-12-03
  • 2019-05-30
相关资源
最近更新 更多