C++ 如何在C++中将数组中的所有数字相加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26941943/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:42:30  来源:igfitidea点击:

How to add all numbers in an array in C++?

c++arraysaddition

提问by ShadowWesley77

Instead of typing

而不是打字

array[0] + array[1] //.....(and so on)

is there a way to add up all the numbers in an array? The language I'm using would be c++ I want to be able to do it with less typing than I would if I just typed it all out.

有没有办法将数组中的所有数字相加?我使用的语言将是 c++ 我希望能够以比我将它全部输入时更少的输入来完成它。

采纳答案by Kiersten Jay Raymond

Try this:

尝试这个:

int array[] = {3, 2, 1, 4};
int sum = 0;

for (int i = 0; i < 4; i++) {
    sum = sum + array[i];
}
std::cout << sum << std::endl;

回答by dasblinkenlight

Here is the idiomatic way of doing this in C++:

这是在 C++ 中执行此操作的惯用方法:

int a[] = {1, 3, 5, 7, 9};
int total = accumulate(begin(a), end(a), 0, plus<int>());

Demo.

演示。

回答by Red Alert

Say you have an int array[N].

假设你有一个int array[N].

You can simply do:

你可以简单地做:

int sum = 0;
for(auto& num : array)
    sum += num;

回答by jbo5112

If you use a valarray, there is a member function sum()for that.

如果您使用 a valarray,则有一个成员函数sum()

#include <iostream>     // std::cout
#include <valarray>     // std::valarray

int main () {
  std::valarray<int> myvalarray(4);
  myvalarray[0] = 0;
  myvalarray[1] = 10;
  myvalarray[2] = 20;
  myvalarray[3] = 30;
  std::cout << "The sum is " << myvalarray.sum() << '\n';

  return 0;
}

回答by FlyingPiMonster

The easiest way I can see to do this is to use a loop. The bonus is that you can use it on any integer array without rewriting much code at all. I use Java more often, so I hope there aren't too many syntax errors, but something like this should work:

我能看到的最简单的方法是使用循环。好处是您可以在任何整数数组上使用它,而无需重写太多代码。我更经常使用 Java,所以我希望没有太多的语法错误,但这样的事情应该可行:

int addArray(int[] array, int length){
    int sum=0;
    for(int count=0;count<length;count++){
        sum+=array[count];
    }
    return sum;
}

回答by Mohammad Alaggan

In C++17, one could use fold expressions:

在 C++17 中,可以使用折叠表达式:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

If sum_implhad a constant number of parameters, we could have called it like this:

如果sum_impl有固定数量的参数,我们可以这样称呼它:

std::apply(sum_impl, arr);

assuming arr is std::array<int, N>. But since it is variadic, it needs a little push with helpers:

假设 arr 是std::array<int, N>。但由于它是可变参数,因此需要使用助手进行一些推动:

using namespace std;

template <class Array, size_t... I>
int sum_impl(Array&& a, index_sequence<I...>)
{
        return sum_impl(get<I>(forward<Array>(a))...);
}

template <class Array>
int sum(Array&& a)
{
        return sum_impl(forward<Array>(a),
                        make_index_sequence<tuple_size_v<decay_t<Array>>>{});
}

Therefore, assuming these helpers are in place, the code will look something like this:

因此,假设这些助手已就位,代码将如下所示:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

int main()
{
    array<int, 10> arr{0,1,2,3,4,5,6,7,8,9};
    cout << sum(arr) << "\n";
    return 0;
}

回答by rashedcs

We may use user defined function.

我们可以使用用户定义的函数。

Code Snippet :

代码片段:

#include<bits/stdc++.h>
using namespace std;


int sum(int arr[], int n)
{
    int sum=0;

    for(int i=0; i<n; i++)
    {
        sum += arr[i];
    }
    return sum;
}


int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  int n = distance(begin(arr), end(arr));

  int total = sum(arr,n);

  printf("%d", total);

  return 0;
}

回答by Name_Guest

int Sum;
for(int& S: List) Sum += S;