将两个数组作为参数传递,并在 c++ 中计算它们的总和
Passing two arrays as parameters and calculating the sum of them in c++
>编写一个函数,它将两个数组作为参数并添加单个 元素将每个数组组合在一起,使得 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::vector
与std::transform
一起使用,std::plus<int>()
。 像这样:
std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
如果你坚持使用普通数组(这里假设a
和b
是数组),那么你可以做这样的事情:
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
,简单的选项如下。
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;
}
- 当通过引用传递时,你可以推断数组的大小,这在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;
}
那么常见的大小是A
和B
的最小值。
- 你可以使用
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算法(最近倾向于获取并行和非顺序重载),尽管它需要少量的额外工作(有点太大而无法容纳此裕度)。
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 计算缩放多边形的比例,得到给定的多边形面积
- 在C++中如何在没有pow的情况下进行基础计算
- 计算平均值,不包括上次得分
- 如何计算多映射中重复对的数量