繁体   English   中英

在 C++ 中添加一组数字

[英]Add a set of numbers in C++

我知道我可以先将数字存储在数组中,例如 arr[] = {1,2,3}; 然后调用 sum 函数将所有数字相加,如 sum(arr);

但是如果我不想使用 arr[] 而只是调用 sum(1,2,3) 呢?

这些值将由用户确定,因此可以是 sum(1,2)、sum(1,2,3,4,5) 或 sum(1,2,5)

#include <iostream>
#include <math.h>
using namespace std;

int addition (int arr[]) {
    int length = log2(*(&arr + 1) - arr);
    int res = 0;
    for (int n=0; n<length + 1; n++){
        res += arr[n];
    }
    cout << res << endl;
    return 0;
}

int main ()
{
  int array[] = {5, 10, 15,20};
  int array1[] = {10,15,20,25,30};
    
  addition (array);
  addition (array1);

  return 0;
}

你可以这样写函数:

template<typename ...Ts>
auto sum(Ts ...ts)
{
    int arr[]{ ts... };
    addition(arr);
}

它将可变参数存储到一个数组中,并在该数组上调用addition

这是一个演示


但是,您也可以像这样简单地编写sum

template<typename ...Ts>
auto sum(Ts ...ts)
{
    return (ts + ...);
}

这是一个演示


此外,如果您使用std::vector而不是数组,则可以像这样编写addition

void addition (std::vector<int> const & v) {
    std::cout << std::accumulate(v.begin(), v.end(), 0) << "\n";
}

这是一个演示 请注意,您也可以对数组使用accumulate ,但该函数必须是一个模板,如下所示:

template<int N>
void addition (int const (&arr)[N]) {
    std::cout << std::accumulate(arr, arr + N, 0) << "\n";
}

这是一个演示

另一种选择是使用 stringstreams 来处理该过程。 我想可变参数模板方法@cigien 会更有效,但字符串流对于许多目的确实很有用:

#include <sstream>
#include <iostream>

int ssum(std::stringstream &obj) {
    int accumulator = 0;
    std::string buffer;
    while (obj >> buffer) {            //read the stream number by number
        accumulator += stoi(buffer);   //convert to int and add
    }
    return accumulator;
}

int main() {
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
    std::stringstream os;
    for (auto i : arr) {                  //feed the array into the stream obj
        os << i << " ";
    }
    std::cout << ssum(os) << std::endl;
    return 0;
}

[编辑删除字符串转换步骤,直接传递stringstream对象]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM