I would like to be able to write something like
char f(char);
vector<char> bar;
vector<char> foo = map(f, bar);
The transform function appears to be similar, but it will not autogenerate the size of the resultant collection.
I would like to be able to write something like
char f(char);
vector<char> bar;
vector<char> foo = map(f, bar);
The transform function appears to be similar, but it will not autogenerate the size of the resultant collection.
You can mimic the map syntax above with something like
template<typename T, typename A>
T map(A(*f)(A), T & container) {
T output;
std::transform(container.begin(), container.end(), std::back_inserter(output), f);
return output;
}
The std::transform function does the job, but isn't performant in some cases. I would suggest using a while loop and reserving the size before hand. This function can easily be changed to be used with strings or any thing mappable for that matter.
template<typename T, typename C>
std::vector<T> map(const std::vector<C> &array, auto iteratee) {
int index = -1;
int length = array.size();
std::vector<T> v(length);
while(++index < length) {
v[index] = iteratee(array[index], index);
}
return v;
}
Calling the function where array is the std::vector you want to
map.
auto result = map<int, int>(array, [](int elem, int index) {
return elem + 10;
});
Running map on 100 000 000
with std::transform took ~6.15s
the while loop version took ~3.90s