Accumulate function in C++
What is the accumulate() function in C++?
The accumulate() function makes it easier to find the sum or combine elements in a range defined by the 'first' and 'last' iterators. It avoids the requirement for a linear operation in which every single value in the range is added one by one, and the result is saved in a variable.
By default, the accumulate() method in C++ accumulates all elements inside a range. However, as a third input, we can define an alternative binary operation through the use of a function pointer or lambda expression. This property enables the accumulation function incredibly versatile, letting it be used for tasks beyond simple addition, such as determining the product of a range of numbers.
The syntax of the C++ accumulate() function
The general syntax of the C++ accumulate() function is as follows:
accumulate(Start_Range, End_Range, Initial_Value);
However, when combined with a user-defined binary predicate, the syntax looks
accumulate(Start_Range, End_Range, Initial_Value,CustomPredicateDefinition);
The parameters of the C++ accumulate() function
The accumulate() method in C++ normally accepts three mandatory parameters, which are named.
- Start_Range - defines the position in the sequence where we would like the operation to begin.
- End_Range - indicates the location in the series in which we need to perform the given action.
- Initial_Value - The initial value is passed to the accumulate() function. For example, while calculating the sum, we shall pass Initial_Value as 0 because it represents the basic additive identity for additions, but we can alternatively pass some other value to it. Then, the adding process will begin with the given value as the starting point.
The accumulate() function accepts an optional parameter that specifies the type of operation to be performed. The procedure must always be performed separately from the addition. We can perform multiplication, division, or whatever we choose. The fourth parameter takes a function that informs the accumulate() function what operation to do. We may pass any custom function we desire.
The accumulate() method with additional parameters has the following syntax.
accumulate(Start_Range, End_Range, Initial_Value, call_function) is a function that accumulates values.
The value returned by the C++ accumulate() function
In C++, the accumulate() method gives the accumulated value of the range supplied as an argument. It is determined by the fourth parameter, the function we supply to train the function, and the job it must accomplish, which might be addition, multiplication, or any other function defined.
In the example of arrays or vectors, it normally gives a numerical addition of the provided range if nothing is supplied.
Exceptions to the accumulate() method in C++
When called with invalid parameters, the C++ accumulate() function could show undefined behavior.
How does the C++ accumulate() function works?
The C++ accumulate() function accepts a range of values as inputs along with the beginning value and executes operations on them. In the absence of any input, the function executes addition and gives the added result.
Still, we may call the C++ accumulate() function using an additional fourth parameter and define the operation type directly.
Predicates:
Predicates are used to accumulate functions. A predicate is a function that gives a boolean value. The binary predicate indicates a function that takes two parameters (thus the binary) and returns a boolean value.
Let's look at an example to grasp this better.
Built-in binary predicate
In this example, we will use a built-in binary predicate to figure out the product of a vector.
Code:
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
vector<int> vec{24,45,56,45,34};
// Call the accumulate() function
int prod_val = accumulate(vec.begin(), vec.end(), 1, multiplies < int > ());
// Display the result
cout << "The product value is " << prod_val << endl;
return 0;
}
Output:
![Accumulate function in C++](https://static.tutorialandexample.com/cpp/accumulate-function-in-cpp1.png)
Examples
As previously explained, the accumulate() function supports a variety of operations, some of which are listed below:
Example 1: Using the C++ accumulate() Function to Add a Range of Integers
In C++, you can use the accumulate() method to sum a range of numbers, and the code for this scenario is supplied below:
Code:
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
vector<int> Nums = {12, 23, 32, 14, 25};
int Sum = accumulate(Nums.begin(), Nums.end(), 0);
cout << "The Sum of Nums is: " << Sum << endl;
return 0;
}
Output:
![Accumulate function in C++](https://static.tutorialandexample.com/cpp/accumulate-function-in-cpp2.png)
This code demonstrates how to use the accumulate() method, which computes the sum of vector Nums elements and displays its output to the console through cout. The starting value in the code above is 0.
Example 2: Using the C++ accumulate() function with a Custom Function
You may also implement the accumulate() function using a custom function to get the product of elements in a range, as shown in the code below:
Code:
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int custom_func(int p, int q) {
return p * q;
}
int main() {
vector<int> vec = {14, 24, 27, 18, 35};
int Product = accumulate(vec.begin(), vec.end(), 1, custom_func);
cout << "The vector product is " << Product << endl;
return 0;
}
Output:
![Accumulate function in C++](https://static.tutorialandexample.com/cpp/accumulate-function-in-cpp3.png)
The C++ function accumulate() is used in the code above to demonstrate its use. Using a unique multiplication function called custom_func(), it determines the product of the components in a vector named vec. The outcome is then printed to the console using cout.
Example 3: Concatenating Strings Using the C++ accumulate() Function
Another benefit of utilizing the accumulation function is that you may quickly concatenate strings in a vector; an illustration of this is shown below:
Code:
#include <numeric>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main() {
vector<string> vec = {"Namaste", ", ", "viewers"};
string outcome = accumulate(vec.begin(), vec.end(), string(""));
cout << "The concatenated string is: " << outcome << endl;
return 0;
}
Output:
![Accumulate function in C++](https://static.tutorialandexample.com/cpp/accumulate-function-in-cpp4.png)
With an empty string set as the initial value, the above-mentioned programs construct a vector of strings called vec and concatenate them. The finished concatenated string is then printed to the console using cout.
std::accumulate() function example program in C++
Code:
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main()
{
// Creating of a vector
vector<int> Vect{2,5,7,6,8,9,10};
// considering initial sum as 0
int Sum = 0;
cout << "\n The initial Sum value = " << Sum << endl;
Sum = accumulate(Vect.begin(), Vect.end(), Sum);
cout << " After accumulate, the value Sum is = " << Sum << endl;
// Modifying the value of initial_sum to 25
Sum = 60;
cout << "\n Initial Sum value = " << Sum << endl;
// Displaying the accumulate function
// with additional argument
// Here additional argument will
// subtract all the elements from the
// initial sum. Additional argument could be
// any certain operation
Sum = accumulate(Vect.begin(), Vect.end(), Sum, minus<int>());
cout << " After accumulate function, the sum value with optional argument = " << Sum << endl;
return 0;
}
Output:
![Accumulate function in C++](https://static.tutorialandexample.com/cpp/accumulate-function-in-cpp5.png)
Explanation:
This C++ code demonstrates how to use the accumulate function from the Standard Template Library (STL) while working with vectors. Let me summarize it for you:
- You begin by including two libraries: "vector" for working with vectors and "bits/stdc++.h" (which includes the majority of frequently used C++ standard libraries).
- You build a vector called Vect inside the main function that contains the following integer values: 2, 5, 7, 6, 8, 9, and 10.
- You print the initial value of an integer variable called Sum after initializing it to zero.
- The sum of each element in the vector Vect is then calculated using the accumulate function and stored in the variable named Sum. This STL method can add all the items in a range—in this case, the complete vector—and add them to the starting value (0 in this example).
- After using accumulate, you output the updated value of Sum. This will be the total of the vector's elements.
- Then you update Sum's value to 60 and print it once more.
- You now use accumulate once more, but this time with minusint>() as a second argument. With this extra input, an action between the elements and the starting total is specified. In this instance, minusint>() takes the initial sum of 60 and subtracts each element from it.
- Finally, after using accumulate with the subtraction operation, you output the updated value of Sum.
In conclusion, this code explains how to add up the elements in a vector using the accumulate function and how to modify its behavior by passing an extra operation argument. All elements are first added to the total, then after adjusting the starting sum value, all elements are subtracted from the sum.