我知道我可以先将数字存储在数组中,例如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
。这是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。
关于c++ - 在C++中添加一组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63642647/