c++ - How can we use std::transform, if we don't want to transform each element into one transformed element, but two? -
how can use std::transform, if don't want transform each element one transformed element, two?
the following pseudo code illustrates want achieve
std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](t const& x) { return f(x) , g(x); }); of course, invoke std::transform 2 times, annoying. maybe need provide custom inserter. other option?
transform doing one-to-one transformation. custom inserter wouldn't anyway since transform implemented this:
while (first1 != last1) { *d_first++ = unary_op(*first1++); // have no way write // more 1 element } return d_first; you have write custom iterator a iterate on each element twice, , keep state in functor know if you're on f state or g state. can see how complicated getting.
anything outside of simple 1-1 transformations, should use for loop:
for (const auto& x : a) { b.push_back(f(x)); b.push_back(g(x)); } and simple 1-1 transformations, think simple range-for expression wins too.
you additionally write own transform takes arbitrary number of functors:
template <typename init, typename outit, typename... functors> void transform(init first, init last, outit d_first, functors... fs) { while (first != last) { apply(*first, d_first, fs...); first++; } } with;
template <typename in, typename outit> void apply(const in&, outit ) { } template <typename in, typename outit, typename f, typename... functors> void apply(const in& in, outit& out, f f, functors... fs) { *out++ = f(in); apply(in, out, fs...); } used (example):
transform(a.begin(), a.end(), back_inserter(b), f, g);
Comments
Post a Comment