【问题标题】:Add a set of numbers in C++在 C++ 中添加一组数字
【发布时间】:2020-08-29 01:39:24
【问题描述】:

我知道我可以先将数字存储在数组中,例如 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;
}

【问题讨论】:

  • 保留问题中的代码,它是相关的。

标签: c++ arrays function sum add


【解决方案1】:

你可以这样写函数:

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

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

这是demo。


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

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

这是demo。


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

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

这是demo。请注意,您也可以将 accumulate 与数组一起使用,但函数必须是模板,如下所示:

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

这是demo。

【讨论】:

  • 我正在考虑使用数组将数字存储在 sum 函数中。这行得通吗?
  • 我想是的。你为什么不添加 sum 来为你的问题添加一个数组?
  • 我做到了。我正在努力解决的部分是如何将这些数字存储在 sum 函数内的数组中。
  • 好的,然后至少显示该代码。在你的问题中,你说你可以做arr[] = {1,2,3}; sum(arr);。显示该代码。
  • 据我所知。实现一个接受任意数量参数的函数需要一个模板。是你不喜欢的语法吗?在 c++20 中,您可以执行 this。不过它仍然是一个模板。
【解决方案2】:

另一个选择是使用字符串流来处理这个过程。我想可变参数模板方法@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对象]

【讨论】:

  • 你能做你的 ssum(1,2,3,4,5) 吗?不使用数组,直接使用数字。
  • 这可能更像是可变参数模板方法(例如,比较像def adder(*args): return sum(args) 这样的python 函数)。它在 C++ 中相当复杂(您必须了解递归概念),但这里有一个很好的来源:eli.thegreenplace.net/2014/variadic-templates-in-c
猜你喜欢
  • 1970-01-01
  • 2012-10-08
  • 2017-06-25
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2017-01-17
相关资源
最近更新 更多