Skip to content

Instantly share code, notes, and snippets.

@takoeight0821 takoeight0821/
Last active Nov 12, 2016

What would you like to do?
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
You can’t perform that action at this time.