accumulate() and partial_sum() in C++ STL
Last Updated :
09 Sep, 2024
accumulate() and partial_sum() functions are used to find the sum or any other accumulated value that is obtained by doing the addition or any other binary operation on the elements in the given range. Both of these functions are the part of STL Numeric Library and defined inside <numeric> header.
std::accumulate()
The std::accumulate() function is used to find the sum (or any other binary operation) of all the values lying in a range.
Syntax
std::accumulate(first, last, init, op);
Parameters
- first: Iterator to the first element of the range.
- last: Iterator to the element one after the last element of the range.
- init: Initial value to start the accumulation with.
- op: An optional function pointer that provides the binary operation to perform. By default, addition is used to get the sum.
Return Value
- Returns the accumulated value after performing the operation on each element.
Examples of std::accumulate()
The below program illustrates how to use std::accumulate() functions in C++ program:
Example 1: Finding the Sum of All Elements of Vector Using std::accumulate()
C++
// C++ program to demonstrate the use of std::accumulate function
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vec = { 5, 10, 15 };
// Defining range as whole array
auto first = vec.begin();
auto last = vec.end();
// Use accumulate to find the sum of elements in the vector
int sum = accumulate(first, last, 0);
cout << sum << endl;
return 0;
}
Example 2: Finding the Product of Vector Elements Using std::accumulate()
C++
// C++ program to demonstrate the working of accumulate()
#include <bits/stdc++.h>
using namespace std;
// Custom function to multiply adjacent numbers
int op(int a, int b) {
return a * b;
}
int main() {
vector<int> vec = {5, 10, 15};
// Defining the range as whole array
auto first = vec.begin();
auto last = vec.end();
// Using accumulate function with user-defined operation
int product = accumulate(first, last, 1, op);
cout << product;
return 0;
}
Complexity Analysis of std::accumulate()
std::accumulates works by adding (or performing specified operation on) elements one by one. So, as long as the operation takes constant time, the time complexity will be linear.
- Time Complexity: O(n), where n is the number of elements in the range.
- Auxiliary Space: O(1)
Note: For adding larger values beyond the int range, the sum should be initialized with 0ll or any other value with the suffix ll, else the sum will be overflown. (here ll refers to long long int)
std::partial_sum()
std::partial_sum() function assigns the cumulative sum of all the set of values lying in the given range and stores it in another container at corresponding positions. Just like accumulate() function, we can modify the partial_sum() function to perform any other binary operation.
Syntax
std::partial_sum (first, last, res, op);
Parameters
- first: Iterator to the first element of the range
- last: Iterator to the last elements of range.
- res: iterator to the container (mostly vector) where partial sum will be stored.
- op: An optional function pointer that provides the binary operation to perform. By default, addition is used to get the sum.
Return Value
- Iterator to the imaginary element after the last element in the res container. (end iterator)
Example std::partial_sum()
The following program demonstrate how to use the partial_sum() sum in C++ program.
Example 1: Finding the Cumulative Sum of All Elements of Vector
C++
// C++ program to demonstrate the use of std::partial_sum function
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vec = {5, 10, 15};
vector<int> res(vec.size());
// Defining range as the whole array
auto first = vec.begin();
auto last = vec.end();
// Use partial_sum to calculate the cumulative sum of elements
partial_sum(first, last, res.begin());
for (int val : res)
cout << val << " ";
return 0;
}
Example 2: Finding Cumulative Product of Vector Elements std::partial_sum()
C++
// C++ program to demonstrate the working of partial_sum()
// with custom function
#include <bits/stdc++.h>
using namespace std;
// Custom function to multiply adjacent numbers
int op(int a, int b) {
return a * b;
}
int main() {
vector<int> vec = {5, 10, 15};
vector<int> result(vec.size());
// Defining the range as the whole array
auto first = vec.begin();
auto last = vec.end();
// Using partial_sum with user-defined function (myfun)
partial_sum(first, last, result.begin(), op);
for (int val : result)
cout << val << " ";
return 0;
}
Complexity Analysis of std::accumulate()
std::partial_sum() works in similar way as std::accumulate(). It adds (or performing specified operation) the elements one by one so as long as the operation takes constant time, the time complexity will be linear.
- Time Complexity: O(n), where n is the number of elements in the range.
- Space Complexity: O(1)
Similar Reads
C++ STL Algorithm Library Standard Template Library (STL) offers a rich collection of algorithms designed to operate on STL containers and beyond. It provides commonly used algorithms such as sorting, searching, copying, etc. These well tested algorithms are optimized for performance and provide a way to write cleaner, faste
3 min read
sort() in C++ STL In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++, but it only works on data structures that provide random access to its elements such as vectors and arrays.Let's take a look at an example:C++#include
4 min read
Type Inference in C++ (auto and decltype) Type Inference is a feature in C++, using which the compiler automatically deduces the data type of an expression, function, or variable. Type inference was introduced with C++11 through the use of the auto and decltype.Before C++ 11, each data type had to be explicitly declared, which limited the v
5 min read
transform() in C++ STL In C++, transform() is a built-in STL function used to apply the given operation to a range of elements and store the result in another range. Letâs take a look at a simple example that shows the how to use this function:C++#include <bits/stdc++.h> using namespace std; int main() { vector<i
4 min read
Variadic function templates in C++ Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor
3 min read
Template Specialization in C++ Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type. What if we want a different code for a p
5 min read
Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge, Some of the merge operation classes are provided in C++ STL under the header file "algorithm", which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container
7 min read
std::partition in C++ STL C++ has a class in its STL algorithms library which allows us easy partition algorithms using certain inbuilt functions. Partition refers to act of dividing elements of containers depending upon a given condition. Partition operations :1. partition(beg, end, condition) :- This function is used to pa
5 min read
accumulate() and partial_sum() in C++ STL accumulate() and partial_sum() functions are used to find the sum or any other accumulated value that is obtained by doing the addition or any other binary operation on the elements in the given range. Both of these functions are the part of STL Numeric Library and defined inside <numeric> hea
4 min read
numeric header in C++ STL | Set 2 (adjacent_difference(), inner_product() and iota()) The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header: iotaaccumulatereduceinner_productpartial_sum etc.
4 min read