Cover Image for accumulate() and partial_sum() in C++ STL : Numeric header
113 views

accumulate() and partial_sum() in C++ STL : Numeric header

The accumulate() and partial_sum() are two commonly used functions from the C++ Standard Library’s <numeric> header for performing operations on sequences of values, typically in a container like a vector or an array.

  1. accumulate() Function:
    std::accumulate() computes the sum of all the elements in a range.
C++
 #include <iostream>
 #include <vector>
 #include <numeric>

 int main() {
     std::vector<int> numbers = {1, 2, 3, 4, 5};
     int sum = std::accumulate(numbers.begin(), numbers.end(), 0);

     std::cout << "Sum of elements: " << sum << std::endl;
     return 0;
 }

In this example, std::accumulate() adds up all the values in the numbers vector, starting with an initial value of 0.

  1. partial_sum() Function:
    std::partial_sum() computes the partial sums of the elements in a range and stores them in another range or container.
C++
 #include <iostream>
 #include <vector>
 #include <numeric>

 int main() {
     std::vector<int> numbers = {1, 2, 3, 4, 5};
     std::vector<int> partial_sums(numbers.size());

     std::partial_sum(numbers.begin(), numbers.end(), partial_sums.begin());

     std::cout << "Partial Sums: ";
     for (const int& num : partial_sums) {
         std::cout << num << " ";
     }
     std::cout << std::endl;

     return 0;
 }

In this example, std::partial_sum() calculates and stores the partial sums in the partial_sums vector. The output will be “Partial Sums: 1 3 6 10 15,” which are the cumulative sums of the original vector.

Both accumulate() and partial_sum() are powerful tools for performing operations on sequences of values, and they can be customized with different binary operators and initial values to perform various calculations beyond simple addition.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS