Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional version of std::transform

Tags:

c++

When applying a function to a collection of elements, std::transform takes the output as 3rd parameter. Is there version which returns the result, something like vec2 = map(func, vec1)?

like image 516
Micha Wiedenmann Avatar asked Jul 16 '26 19:07

Micha Wiedenmann


1 Answers

No, there is nothing like that in the standard library. You can write one yourself:

template<typename T, typename Func>
std::vector<T> transform(std::vector<T> const &input, Func func) {
    std::vector<T> result(input.size());
    std::transform(input.begin(), input.end(), result.begin(), func);
    return result;
}

A better solution may be to use transformed adaptor from Boost.Range as it does not allocate additional container.

like image 131
Juraj Blaho Avatar answered Jul 18 '26 09:07

Juraj Blaho