Calculate sum of elements in a sequence with algorithm accumulate - C++ STL Algorithm

C++ examples for STL Algorithm:accumulate

Description

Calculate sum of elements in a sequence with algorithm accumulate

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <numeric> // accumulate is defined here 
#include <vector> 
#include <iterator> 
using namespace std; 

int main() { /*  w ww  .ja  v a  2  s  .c o m*/
   const int SIZE = 10; 
   int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
   vector< int > v( a1, a1 + SIZE ); // copy of a1 
   ostream_iterator< int > output( cout, " " ); 

   // calculate sum of elements in v 
   cout << "\n\nThe total of the elements in Vector v is: " << accumulate( v.begin(), v.end(), 0 ); 

}

Result


Related Tutorials