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.
std::reduce()
AlgorithmC++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()
and fold_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()
and fold_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:
std::optional
when using fold_left_first()
or fold_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()
.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 6 new folding algorithms added in C++23, providing alternatives to std::reduce
and std::accumulate