C++ Standard Library C++ STL Library

C++ <valarray> - sum() Function



The C++ valarray::sum function returns the sum of all elements of a valarray. It uses operator+= to calculate the sum of elements. If the size of the valarray is zero, the behavior is undefined.

Syntax

T sum() const;

Parameters

No parameter is required.

Return Value

Returns the sum of all elements of the valarray.

Time Complexity

Depends on library implementation.

Example:

In the example below, the valarray::sum function is used to find out the sum of all elements of given valarray.

#include <iostream>
#include <valarray>
using namespace std;
 
int main (){
  valarray<int> varr = {1, 2, 3, 4, 5};

  //finding sum of all
  //elements of the valarray
  cout<<"Sum of all elements: "
      <<varr.sum();  

  return 0;
}

The output of the above code will be:

Sum of all elements: 15

❮ C++ <valarray> Library