Last active
November 12, 2016 13:01
-
-
Save takoeight0821/730719c448ee1b9ba55f8f354cbbba16 to your computer and use it in GitHub Desktop.
Map function on C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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