×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

How to find the sum of elements of a vector in C++ STL?

C++ STL | finding sum of the vector elements: Here, we are going to learn how to find the sum of the elements of a vector in C++ STL?
Submitted by IncludeHelp, on May 18, 2019

Given a vector and we have to find the sum of the elements using C++ program.

Finding sum of vector elements

To find the sum of the elements, we can use accumulate() function which is defined in <numeric> header in C++ standard template library. It accepts the range of the iterators in which we have to find the sum of the elements; it also accepts a third parameter which can be used to provide an initial value of the sum.

Note: To use vector – include <vector> header, and to use sum() function – include <numeric> header or we can simply use <bits/stdc++.h> header file.

Syntax

sum(iterator start, iterator end, initial_sum_value);

Here, start_position, iterator end_position are the iterators pointing to the start and end elements in a container to be reversed.
initial_sum_value – is an initial value of the sum that will be added to the result of the sum of the elements.

Example

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

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

C++ STL program to find the sum of the vector elements

//C++ STL program to find the sum of the vector elements
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

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

    //printing elements
    cout << "vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //finding sum with initial value of sum is 0
    int sum = accumulate(v1.begin(), v1.end(), 0);
    cout << "sum (with intial value of sum is 0): " << sum << endl;

    //finding sum with initial value of sum is 100
    sum = accumulate(v1.begin(), v1.end(), 100);
    cout << "sum (with intial value of sum is 100): " << sum << endl;

    return 0;
}

Output

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

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.