How do I use std::accumulate and reduce in C++?

C++ provides powerful algorithms for aggregating values, such as `std::accumulate` and `std::reduce`. These functions are part of the `` header and are useful for summing items or performing other operations on collections.

Using std::accumulate

The `std::accumulate` function is used to compute the sum of elements in a range, but it can also be used to implement other operations like multiplication, concatenation, etc.

Example of std::accumulate:

#include <numeric> #include <vector> #include <iostream> int main() { std::vector numbers = {1, 2, 3, 4, 5}; int sum = std::accumulate(numbers.begin(), numbers.end(), 0); std::cout << "Sum: " << sum << std::endl; return 0; }

Using std::reduce

The `std::reduce` function (introduced in C++17) is similar to `std::accumulate`, but it allows parallel execution and is generally used for more complex cases.

Example of std::reduce:

#include <numeric> #include <vector> #include <iostream> int main() { std::vector numbers = {1, 2, 3, 4, 5}; int sum = std::reduce(numbers.begin(), numbers.end(), 0); std::cout << "Sum: " << sum << std::endl; return 0; }

std::accumulate std::reduce C++ algorithms numeric header