C++ 如何在C++中将两个数组相加?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20579589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add two arrays together in C++?
提问by chasethewhiterabbitt
I need to add two arrays together. Why does the following how work?
我需要将两个数组相加。为什么下面是如何工作的?
#include <iostream>
using namespace std;
int main ()
{
int sumvals[3];
int nums[3];
sumvals [0] = 1;
sumvals [1] = 2;
sumvals [2] = 3;
for (i=0; i <= 3; i++)
{
sumvals[i] = sumvals[i] + numbs [i];
cout << "the sum of the array elements is: " << sumvals << endl;
}
回答by nhgrif
First, your for loop is wrong. Should be i < 3
, not <=
.
首先,你的 for 循环是错误的。应该是i < 3
,不是<=
。
Second, you haven't initialized nums[]
.
其次,你还没有初始化nums[]
.
Third, your for loop is referencing a non-existent numbs[]
.
第三,您的 for 循环引用了一个不存在的numbs[]
.
Fourth, i
is never declared.
第四,i
从不声明。
Fifth, you're printing the result before you're done computing it.
第五,在完成计算之前打印结果。
Sixth, you're not computing a sum, actually.
第六,实际上你不是在计算一个总和。
I have a feeling this is closer to what you're trying to accomplish:
我有一种感觉,这更接近你想要完成的事情:
int nums[3];
int sumvals = 0;
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
for (int i=0; i < 3; ++i) {
sumvals += nums[i];
}
cout << "the sum of the array elements is: " << sumvals << endl;
If you're trying to add the values of two array elements and store them in an array, the syntax is as simple as:
如果您尝试将两个数组元素的值相加并将它们存储在一个数组中,则语法非常简单:
arr1[i] = arr2[i] + arr3[i];
But this assumes that the arrays have been declared and arr2
and arr3
have been initialized.
但这种假设阵列已经申报并arr2
和arr3
已被初始化。
回答by Floris
Summing the elements of two arrays is done like this:
对两个数组的元素求和是这样完成的:
#include <iostream>
int main ()
{
int sumvals[3] = {1, 2, 3}; // initialize one array
int nums[3] = {5, 6, 7}; // initialize the second array
for (i=0; i < 3; i++)
{
sumvals[i] += nums [i]; // aggregate the sums into the first array
}
// print the result:
std::cout << "The sum of the arrays is ";
for( i = 0; i < 3; i++) std::cout << sumvals[i] << " ";
std::cout << std::endl;
}
回答by Shoe
When working with C++ for the first time, my suggestion is: forget everything that is C related and has a C++ counterpart.
In this case stop using C-style arrays and use std::array
instead (the same can be done with std::vector
but I'll leave it as exercise to reader).
当第一次使用 C++ 时,我的建议是:忘记所有与 C 相关并且有 C++ 对应的东西。在这种情况下,请停止使用 C 风格的数组并std::array
改用(也可以这样做,std::vector
但我将把它留给读者作为练习)。
Ok, you want to learn C++? Here's how your problem, of calculating the sum of all the elements of the arrays, can be solved in 3 lines of code using C++:
好的,你想学习C++吗?以下是如何使用 C++ 在 3 行代码中解决计算数组所有元素总和的问题:
#include <iostream>
#include <array>
#include <algorithm>
int main(int, char**) {
std::array<int, 3> nums { 1, 2, 3 };
int sumvals = std::accumulate(std::begin(nums), std::end(nums), 0);
std::cout << "The sum of the array elements is: " << sumvals << std::endl;
}
The explanation is really simple: in the first line we are allocating an array of 3 elements of type int
and initialize it with the three values 1, 2, 3
. Of course you can change those values to something else or initialize them like this:
解释非常简单:在第一行中,我们分配了一个包含 3 个类型元素的数组,int
并使用三个值对其进行初始化1, 2, 3
。当然,您可以将这些值更改为其他值或像这样初始化它们:
std::array<int, 3> nums;
// ...
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
The most important thing to understand here, is that std::array
act just like C-style arrays but they are more powerful and flexible to use.
这里要理解的最重要的事情是,它的std::array
行为就像 C 风格的数组,但它们更强大,使用起来更灵活。
In the second line we use std::accumulate
, a standard algorithm located in <algorithm>
(who would have guessed) to calculate the sum of all the elements of a container (in our case nums
). The algorithm is pretty simple and you can picture is as the equivalent of:
在第二行中,我们使用std::accumulate
了一个标准算法<algorithm>
(谁会猜到)来计算容器中所有元素的总和(在我们的例子中nums
)。该算法非常简单,您可以想象它相当于:
int init = 0;
for (int i = 0; i < 3; ++i)
init += nums[i];
return init;
for your own specific case. The only big difference it that it uses iteratorsinstead. What are iterators? Well, that's something you'll have to research on your own. I can guarantee you there are plenty of articles and posts on the web that will explain it. I'd suggest you to start from here, for example.
对于您自己的具体情况。唯一的大区别是它使用迭代器。什么是迭代器?嗯,这是你必须自己研究的东西。我可以向你保证,网上有很多文章和帖子可以解释它。例如,我建议你从这里开始。
Just remember that std::begin
will retrieve the iterator to the first element of the array, and std::end
will calculate the iterator to the past-the-end element of the array. The use of those functions are pretty common with standard algorithms and you should get used to it. The general ideas of
请记住,std::begin
它将检索到数组第一个元素std::end
的迭代器,并将计算迭代器到数组的最后一个元素。这些函数的使用在标准算法中很常见,您应该习惯它。的一般想法
std::accumulate(std::begin(nums), std::end(nums), 0);
is
是
Calculate the sum of all the elements of the container starting at
std::begin(nums)
and ending at (excluding)std::end(nums)
, given an initial value of0
.
计算容器的所有元素的总和,从
std::begin(nums)
(不包括)开始到结束std::end(nums)
,给定初始值为0
。
As you can, see the function signature and parameters are pretty straight forward. And finally, in the last line, we print out our result (just like we you did before).
如您所见,函数签名和参数非常简单。最后,在最后一行,我们打印出我们的结果(就像我们之前所做的那样)。
回答by Yatharth Agarwal
To add to the others answers, if you want to add two arrays togetherand simply write arr1 + arr2
or arr1 += arr2
, I think these C++11 solutions are OK:
要添加到其他答案中,如果您想将两个数组添加在一起并简单地编写arr1 + arr2
or arr1 += arr2
,我认为这些 C++11 解决方案是可以的:
template<typename T, unsigned long N>
array<T, N>& operator+=(array<T, N>& thi, const array<T, N>& oth) {
for (int i = 0; i < N; ++i)
thi.at(i) += oth.at(i);
return thi;
}
template<typename T, unsigned long N>
array<T, N> operator+(const array<T, N>& a, const array<T, N>& b) {
array<T, N> sum = a;
sum += b;
return sum;
}
回答by Shivam Singh
I hope this will help you:
我希望这能帮到您:
#include<iostream>
using namespace std;
int add(int arr1[],int arr2[],int m,int n)
{
int i=0,j=0,k=0,size = 0;
if(m>n)
size = m;
else
size = n;
cout<<size<<endl;
int res[size] = {0};
while(i<m||j<n)
{
res[k++] = ((i<m)?arr1[i++]:0) +( (j<n)?arr2[j++]:0);
}
for(k=0;k<size;k++)
cout<<res[k]<<" ";
}
int main()
{
int arr1[] = {1,2,3,5,6};
int arr2[] = {3,4,1};
int m,n;
m = sizeof(arr1)/sizeof(arr1[0]);
n = sizeof(arr2)/sizeof(arr2[0]);
add(arr1,arr2,m,n);
return 0;
}