Skip to content

Instantly share code, notes, and snippets.

@takoeight0821
Last active November 12, 2016 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takoeight0821/730719c448ee1b9ba55f8f354cbbba16 to your computer and use it in GitHub Desktop.
Save takoeight0821/730719c448ee1b9ba55f8f354cbbba16 to your computer and use it in GitHub Desktop.
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