Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C++

Idiom #189 Filter and transform list

Produce a new list y containing the result of the function T applied to all elements e of the list x that match the predicate P.

#include <ranges>
#include <iterator>
constexpr auto transform_matches(const auto& x, auto p, auto t) {
    auto result = x 
	| std::views::filter(p)
        | std::views::transform(t);

    std::vector<std::ranges::range_value_t<decltype(result)>> y;
    std::copy(result.begin(), result.end(), std::back_inserter(y));
    return y;
}

Can just return the first line if you don't actually need a vector, and just need something with begin and end.
template <typename SeqT>
auto transform_copy_if(const SeqT i, auto p, auto f)
{
 using namespace std;

 SeqT o;

 for_each(begin(i), end(i),
          [&](const auto& x) {
              if(p(x))
               o.push_back(f(x));
          }
         );

 return o;
}
(def y 
  (eduction (filter P)
            (map T))
            x)

New implementation...