Welcome to a deep dive into one of C++17's powerful algorithms: std::transform_reduce! This tutorial is designed for both beginners and intermediates, so let's get started.
In C++, transforming a range of elements and then reducing the result is a common operation. Before C++17, we had to use separate functions like std::for_each and std::reduce to achieve this. std::transform_reduce combines both operations, making the code more readable and efficient.
std::transform_reduce works on a range of elements, transforms each element using a given function, and then reduces the transformed sequence to a single value using another function.
Here's the general syntax:
template <class InputIterator, class T, class BinaryOperation, class UnaryOperation>
typename std::result_of<UnaryOperation(T)>::type
transform_reduce(InputIterator first, InputIterator last, T init, BinaryOperation op, UnaryOperation unary_op);InputIterator: The type of iterator to the first and last elements of the range.T: The type of the initial value and the type of the accumulated result.BinaryOperation: The binary operation applied to two elements of the transformed sequence.UnaryOperation: The unary operation applied to the accumulated result after each binary operation.Let's sum an array of numbers using std::transform_reduce.
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = std::transform_reduce(numbers.begin(), numbers.end(), 0, [](int a, int b) { return a + b; }, [](int a) { return a; });
std::cout << "Sum: " << sum << std::endl;
return 0;
}In this example, we're summing an array of numbers using std::transform_reduce. The initial value is 0, the binary operation is +, and the unary operation is the identity function (which does nothing but returns its argument).
Let's find the product of the odd numbers in an array using std::transform_reduce.
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int product = std::transform_reduce(numbers.begin(), numbers.end(), 1, [](int a, int b) { return (a % 2 != 0 && b % 2 != 0) ? a * b : a; }, [](int a) { return a; });
std::cout << "Product of odd numbers: " << product << std::endl;
return 0;
}In this example, we're finding the product of the odd numbers in an array. The initial value is 1, the binary operation checks if both numbers are odd before multiplying them, and the unary operation does nothing but returns its argument.
What does the `UnaryOperation` in `std::transform_reduce` do?
In the second example, why is the initial value of the product set to 1?