Difference Between Reduce and Fold Algorithms
What is the difference between std::reduce()
and the new fold algorithms introduced in C++23?
The main difference between std::reduce()
and the new fold algorithms introduced in C++23 lies in the additional flexibility and control provided by the latter.
The std::reduce()
Algorithm
- This function is part of the C++17 standard and is used to reduce a range of elements to a single value using a binary operation.
- It processes elements in a range sequentially, combining them using the provided operation.
- The initial value can be specified, but it does not offer variations for different folding strategies.
New Fold Algorithms in C++23
C++23 introduced six new fold algorithms to provide more control and options when reducing collections of elements. These algorithms are:
std::ranges::fold_left()
std::ranges::fold_left_first()
std::ranges::fold_left_with_iter()
std::ranges::fold_left_first_with_iter()
std::ranges::fold_right()
std::ranges::fold_right_last()
The key differences are:
Direction of Folding:
fold_left()
processes elements from left to right, starting with the first element.fold_right()
processes elements from right to left, starting with the last element.
Initial Value:
fold_left_first()
andfold_right_last()
allow folding without explicitly providing an initial value by using the first or last element of the range, respectively.
Iterator and Sentinel:
fold_left_with_iter()
andfold_left_first_with_iter()
return additional information about the iterator where the folding process stopped. This is useful when you need to know where the range ended.
Handling Empty Ranges:
- The fold algorithms return a
std::optional
when usingfold_left_first()
orfold_right_last()
, which helps in handling cases where the input range might be empty.
Here's a simple example comparing std::reduce()
and std::ranges::fold_left()
:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers{1, 2, 3, 4, 5};
// Using std::reduce()
int reduce_result = std::reduce(
numbers.begin(), numbers.end(), 0, std::plus<>());
std::cout << "Reduce result: "
<< reduce_result << "\n";
// Using std::ranges::fold_left()
int fold_left_result = std::ranges::fold_left(
numbers, 0, std::plus<>());
std::cout << "Fold left result: "
<< fold_left_result << "\n";
}
Reduce result: 15
Fold left result: 15
In summary, the new fold algorithms in C++23 offer more flexibility and control over the folding process, with variations that handle different scenarios, such as folding direction and range termination, more gracefully than std::reduce()
.
C++23 Fold Algorithms
An introduction to the 6 new folding algorithms added in C++23, providing alternatives to std::reduce
and std::accumulate