Skip to content

Instantly share code, notes, and snippets.

@robey
Created April 5, 2012 03:50
Show Gist options
  • Save robey/2307799 to your computer and use it in GitHub Desktop.
Save robey/2307799 to your computer and use it in GitHub Desktop.
my failures with lambda in c++
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
template<typename A, typename Func> auto map_3(const A& orig, Func f) -> std::vector<decltype(f(begin(A())))> {
std::vector<decltype(f(begin(A())))> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
template<typename A, typename Func> auto map_2(const std::vector<A>& orig, Func f) -> std::vector<decltype(f(A()))> {
std::vector<decltype(f(A()))> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
template<typename A, typename B, typename C> std::vector<B> map_(const std::vector<A>& orig, C f) {
std::vector<B> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
std::vector<int> map(const std::vector<int>& orig, const std::function<int(int)> f) {
std::vector<int> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
#if 0
template<typename A, typename B, typename F> B mapXX(const A& orig, const F* f) {
B rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
template<typename A, typename B> std::vector<B> map_(std::vector<A>& orig, auto f(A) -> B) {
std::vector<B> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
#endif
int main(int argc, char **argv) {
std::vector<int> list;
list.push_back(10);
list.push_back(20);
list.push_back(50);
// std::vector<int> transformed;
// transformed.resize(list.size());
// std::transform(begin(list), end(list), begin(transformed), [](int x) -> int { return x + 1; });
// typedef int (*int2int)(int);
// int2int f = [](int x) -> int { return x + 1; };
auto transformed = map_2(list, [](int x) -> int { return x + 1; });
std::for_each(begin(transformed), end(transformed), [](int x) { printf("-> %d\n", x); });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment