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


In this tutorial, we will be discussing a program to understand how to find the sum of elements of a vector using STL in C++.

To find the sum of elements of a given vector, we would be using the accumulate() method from the STL library.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //defining the vector
   vector<int> a = { 1, 45, 54, 71, 76, 12 };
   cout << "Vector: ";
   for (int i = 0; i < a.size(); i++)
      cout << a[i] << " ";
   cout << endl;
   //calculating sum of the elements
   cout << "Sum = "<< accumulate(a.begin(), a.end(), 0);
   return 0;
}

Output

Vector: 1 45 54 71 76 12
Sum = 259

Updated on: 25-Feb-2020

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements