Using fold_left_first()
with custom operators allows you to customize how elements in your collection are combined. This can be particularly useful for operations that are more complex than standard arithmetic.
fold_left_first()
algorithm: fold_left_first()
takes a range and a binary operation but does not require an initial value since it uses the first element of the range as the initial value.Here's an example using a lambda expression as the custom operator to calculate the sum of absolute values:
#include <algorithm>
#include <iostream>
#include <optional>
#include <vector>
int main() {
std::vector<int> numbers{1, -2, 3, -4, 5};
auto abs_sum = [](int x, int y) {
return std::abs(x) + std::abs(y); };
std::optional<int> result =
std::ranges::fold_left_first(numbers, abs_sum);
if (result.has_value()) {
std::cout << "Result: " << result.value();
}
}
Result: 15
abs_sum
takes two integers and returns the sum of their absolute values.std::ranges::fold_left_first(numbers, abs_sum)
uses this lambda to fold the elements of the numbers
vector.std::optional
to handle the case of an empty range.You can also use a function object (functor) for more complex operations:
#include <algorithm>
#include <iostream>
#include <optional>
#include <vector>
struct Multiply {
int operator()(int x, int y) const {
return x * y;
}
};
int main() {
std::vector<int> numbers{1, 2, 3, 4, 5};
std::optional<int> result =
std::ranges::fold_left_first(
numbers, Multiply{});
if (result.has_value()) {
std::cout << "Result: " << result.value();
}
}
Result: 120
Multiply
struct defines an operator()
that multiplies two integers.std::ranges::fold_left_first(numbers, Multiply{})
uses this functor to multiply the elements of the numbers
vector.std::optional
.fold_left_first()
returns a std::optional
, which makes it easy to handle cases where the input range is empty:
#include <algorithm>
#include <iostream>
#include <optional>
#include <vector>
int main() {
std::vector<int> empty_numbers{};
auto sum = [](int x, int y) { return x + y; };
std::optional<int> result =
std::ranges::fold_left_first(
empty_numbers, sum);
if (!result.has_value()) {
std::cout << "The input range is empty";
}
}
The input range is empty
In summary, using fold_left_first()
with custom operators involves defining a custom binary operation and passing it to the algorithm.
This allows for flexible and powerful ways to process collections, handling both standard and complex operations with ease.
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