将两个数组作为参数传递,并在 c++ 中计算它们的总和

Passing two arrays as parameters and calculating the sum of them in c++

本文关键字:计算 c++ 并在 参数传递 两个 数组      更新时间:2023-10-16

>编写一个函数,它将两个数组作为参数并添加单个 元素将每个数组组合在一起,使得 firstArray[i] = firstArray[i] + secondArray[i] 其中 0 <= i <= 4。

int[] sumEqualLengthArrays(int[] a, int[] b) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++)
result[i] = a[i] + b[i];
return result;
}

我已经坚持了一段时间了,我只是无法弄清楚答案是什么。我试图在上面的代码中回答它。我是C++编程的初学者,因为我在空闲时间学习它。这个问题的答案真的很有帮助!

既然你说你可以使用任何东西,那么将std::vectorstd::transform一起使用,std::plus<int>()。 像这样:

std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());

如果你坚持使用普通数组(这里假设ab是数组),那么你可以做这样的事情:

std::transform(a, &a[number_of_elements], b, a, std::plus<int>());

但是,请不要..使用std::vector.

如何使用第一种方法:

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {1, 2, 3};
std::transform(a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
for(auto iter = a.begin(); iter != a.end(); ++iter)
{
std::cout << *iter << std::endl;
}
return 0;
}

如何使用第二种方法:

#include <iostream>
#include <algorithm>
int main()
{
int a[3] = {1, 2, 3};
int b[3] = {1, 2, 3};
std::transform(a, &a[0] + 3, b, a, std::plus<int>());
for(int i = 0; i < 3; ++i)
{
std::cout << a[i] << std::endl;
}
return 0;
}

像这样:

std::vector<int> sumEqualLengthArrays(const std::vector& rhs, 
const std::vector& lhs){
if(lhs.length() == rhs.length()){
std::vector<int> result(rhs.length(), 0);
for(unsigned int i = 0; i < rhs.length; ++i){
result[i] = rhs[i] + lhs[i];
}
return result;
}else{
std::cout << "Length is not equal!" << std::endl;
return rhs;
}
}

我建议使用向量而不是数组,并在使用前检查长度,以防万一。

您已经在问题公式中编写了求和表达式。如果你再看一遍,你会发现结果存储在first中,不需要单独的result数组(在C++中返回数组并不是一件小事)。

而且,说到这一点,将数组作为参数传递也不容易。

假设您不使用std::vector,简单的选项如下。

  1. int a[](注意方括号的位置)作为函数形式参数是指针的同义词。它不包含任何大小信息,因此您必须添加第三个参数,这是两个数组的最小大小:

int *add(int a[], int b[], std::size_t commonSize) { // commonSize is the least of a's and b's sizes for(std::size_t i = 0; i < commonSize; ++i) a[i] += b[i]; return a; }

  1. 当通过引用传递时,你可以推断数组的大小,这在C++中是允许的,并且与经典 C 严重偏离:

template<std::size_t A, std::size_t B> int (&add(int (&a)[A], int (&b)[B]))[A] { for(std::size_t i = 0; i < std::min(A, B); ++i) a[i] += b[i]; return a; }

那么常见的大小是AB的最小值。

  1. 你可以使用std::array,这和上一个选项几乎一样

template<std::size_t A, std::size_t B> void add(std::array<int, A> &a, std::array<int, B> const &b);

通过这种方式,您甚至可以使用范围循环,或者,例如,STL算法(最近倾向于获取并行和非顺序重载),尽管它需要少量的额外工作(有点太大而无法容纳此裕度)。