sum of vector c++ code example

Example 1: sum of vector c++

accumulate(a.begin(), a.end(), 0);

Example 2: sum of elements in c++ stl

accumulate(a.begin(), a.end(), 0)

Example 3: sum elements in vector c++

for (auto& n : vector)
    sum_of_elems += n;

Example 4: sum of vector c++

//Syntax
accumulate(first, last, sum);
accumulate(first, last, sum, myfun); 

first, last : first and last elements of range 
              whose elements are to be added
sum :  initial value of the sum
myfun : a function for performing any 
        specific task. For example, we can
        find product of elements between
        first and last.
//Example
  int a[] = {5 , 10 , 15} ;
  int res = accumulate(a,a+3,0); // 30

Example 5: C++ sum a vector of digits

// Sum digits in vector
int digit_sum(vector<int> num) {
    int sum = 0;
    for (auto x : num) sum += x;
    return sum;
}