Skip to content

Instantly share code, notes, and snippets.

@film42
Last active August 29, 2015 14:03
Show Gist options
  • Save film42/229c3b605bec3f9c68ec to your computer and use it in GitHub Desktop.
Save film42/229c3b605bec3f9c68ec to your computer and use it in GitHub Desktop.
Implementing generic map and reduce functions for certain collections in c++11 using lambda `std::function`
#include <iostream>
#include <vector>
#include <list>
template<typename T, typename V>
T map(T list, std::function<V (V)> fn) {
T new_list;
for(V& value : list) {
new_list.push_back( fn(value) );
}
return new_list;
};
int main(int argc, const char * argv[]) {
//
// On a Vector
//
auto vector_of_ints = std::vector<int> { 1, 2, 3 };
auto exp = map<std::vector<int>, int>( vector_of_ints, [](int val) {
return val * val;
});
for(int val : exp) {
std::cout << val << std::endl; //=> 1, 4, 9
}
//
// Or a List
//
auto list_of_strings = std::list<std::string> { "hi", "hello", "me" };
auto exp2 = map<std::list<std::string>, std::string>( list_of_strings, [](std::string val) {
return val + val;
});
for(std::string val : exp2) {
std::cout << val << std::endl; //=> "hihi", "hellohello", "meme"
}
}
#include <iostream>
#include <vector>
#include <list>
template<typename T, typename V>
V reduce(T list, std::function<V (V, V)> fn) {
V acc;
bool assigned = false;
for(V& value : list) {
if(!assigned) {
acc = value;
assigned = true;
continue;
}
acc = fn(acc, value);
}
return acc;
}
int main(int argc, const char * argv[]) {
//
// Now Reducing on the Vector
//
int reduction = reduce<std::vector<int>, int>(vector_of_ints, [](int acc, int val) {
return acc + val;
});
std::cout << reduction << std::endl; //=> 6
//
// And Reduce the List of Strings
//
auto reduction2 = reduce<std::list<std::string>, std::string>(list_of_strings, [](std::string acc, std::string val) {
return acc + val;
});
std::cout << reduction2 << std::endl; //=> "hihellome"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment