如何在C ++ STL中找到向量元素的总和?

给定一个向量,我们必须使用C ++程序找到元素的总和。

求向量元素之和

找到元素的总和,我们可以使用在C ++标准模板库的<numeric>标头中定义的accumulate()函数。它接受迭代器的范围,我们必须在其中找到元素的总和。它也接受可以用于提供总和初始值的第三个参数。

注意:要使用vector –包含<vector>头文件,而要使用sum()函数–包含<numeric>头文件,或者我们可以简单地使用<bits / stdc ++。h>头文件。

语法:

    sum(iterator start, iterator end, initial_sum_value);

在这里,start_position,迭代器end_position是指向容器中要反转的开始和结束元素的迭代器。
initial_sum_value –是总和的初始值,将被添加到元素总和的结果中。

示例

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50};

    sum(v1.begin(), v1.end(), 0);
    
    Output:
    150

C ++ STL程序查找向量元素的总和

//C ++ STL程序查找向量元素的总和
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int main(){
    //向量
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //打印元素
    cout << "vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //查找和的初始值为0的和
    int sum = accumulate(v1.begin(), v1.end(), 0);
    cout << "sum (with intial value of sum is 0): " << sum << endl;

    //求和的初始值为100-
    sum = accumulate(v1.begin(), v1.end(), 100);
    cout << "sum (with intial value of sum is 100): " << sum << endl;

    return 0;
}

输出结果

vector elements...
10 20 30 40 50
sum (with intial value of sum is 0): 150
sum (with intial value of sum is 100): 250