Map function on C++
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
#include <string> | |
#include <iterator> | |
template <class T, class F> | |
decltype(auto) map(const std::vector<T> a, const F fn) { | |
std::vector<decltype( fn(a[0]) )> result = {}; | |
std::transform(a.cbegin(), a.cend(), std::back_inserter(result), fn); | |
return result; | |
} | |
int main() { | |
const std::vector<int> v = { 3, 5, 6}; | |
const auto result = map(v, [](const int x){return std::to_string(x * 2); }); | |
std::for_each(result.begin(), result.end(), | |
[](const std::string& s) { std::cout << s << std::endl; }); | |
std::for_each(v.begin(), v.end(), | |
[](const int n) { std::cout << n << std::endl; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment