如何使用C++ STL查找数组元素的和
给定一个数组arr [],使用C++ STL查找此数组的元素的总和。
例子:
输入: arr [] = {1, 45, 54, 71, 76, 12}
输出: 259
输入: arr [] = {1, 7, 5, 4, 6, 12}
输出: 35
方法:可以使用STL中提供的accumulate()函数找到总和。
语法:
accumulate(first_index,last_index,sum的初始值);
下面是上述方法的实现:
//使用STL在数组中找到和的C ++程序
#include
using namespace std;
int main()
{
//获取数组
int arr [] = {1, 45, 54, 71, 76, 12};
//计算尺寸
int n = sizeof(arr)/ sizeof(arr [0]);
//打印数组
cout <<“Array:”;
for(int i = 0; i
Array: 1 45 54 71 76 12
Sum = 259