问题描述
我知道我可以先将数字存储在数组中,例如arr [] = {1,2,3}; 然后调用sum函数将所有数字相加,例如sum(arr);
但是,如果我不想使用arr []而只调用sum(1,3)怎么办?
值将由用户确定,因此可以是sum(1,2),sum(1,3,4,5)或sum(1,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,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。
,另一个选择是使用字符串流来处理该过程。我认为可变参数模板方法@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对象]