Daily bit(e) of C++ | std::views::adjacent_transform
1 min readJul 29, 2023
Daily bit(e) of C++ #209, The C++23 view of the applications of an N-ary invocable on consecutive elements: std::views::adjacent_transform.
The C++23 std::view::adjacent_transform is a view that produces elements by continually applying the provided N-ary invocable to each consecutive group of N elements.
The functionality can be simulated by combining std::views::adjacent and std::views::transform, however, this is both less efficient and more cumbersome.
#include <ranges>
#include <vector>
std::vector<int> data{5,1,2,4,3};
auto med3 = [](int a, int b, int c) {
if (a >= b) {
if (b >= c) return b;
if (a >= c) return c;
return a;
} else {
if (c >= b) return b;
if (a >= c) return a;
return c;
}
};
auto medians = data | std::views::adjacent_transform<3>(med3);
// medians == {2, 2, 3}
// Same as the following, but avoiding the intermediate tuple:
auto medians_twostep = data | std::views::adjacent<3> |
std::views::transform([&](auto&& e) {
return std::apply(med3, e);
});
// medians_twostep == {2, 2, 3}
// Simulating the adjacent difference algorithm.
// The pairwise specialization is equivalent to adjacent_transform<2>.
auto adjacent_difference = data |
std::views::pairwise_transform(std::minus<>{});
// adjacent_difference == {4, -1, -2, 1}