C++ STL中的数组和

在C++中,我们可以快速找到数组和 积累

null

// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>
using namespace std;
// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum( int a[], int n)
{
int initial_sum  = 0;
return accumulate(a, a+n, initial_sum);
}
int main()
{
int a[] = {5 , 10 , 15} ;
int n = sizeof (a)/ sizeof (a[0]);
cout << arraySum(a, n);
return 0;
}


输出:

30

向量和

// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum(vector< int > &v)
{
int initial_sum  = 0;
return accumulate(v.begin(), v.end(), initial_sum);
}
int main()
{
vector< int > v{5 , 10 , 15} ;
cout << arraySum(v);
return 0;
}


输出:

30

我们还可以在“累积”中使用自定义函数。参考 C++ STL集1中的数值头(累加器)和部分ALL() 详细信息。

本文由 卡尔蒂克 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享