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

C++Server Side ProgrammingProgramming

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
raja
Published on 25-Feb-2020 09:10:36
Advertisements