Skip to content

Instantly share code, notes, and snippets.

@catphive
Created April 6, 2012 09:54
Show Gist options
  • Save catphive/2318575 to your computer and use it in GitHub Desktop.
Save catphive/2318575 to your computer and use it in GitHub Desktop.
list comprehensions for C++
// Python style list comprehensions for C++.
// Example: multiply all elements of vector literal by 2.
//
// auto vec_doubled = VFOR(std::vector<int>({1,2,3}), x, x * 2);
//
// vec_squared is now equal to std::vector<int>({1,4,6})
#include <vector>
#include <type_traits>
template <typename T, typename Function,
typename ResultType = std::vector<typename std::result_of<Function(const T&)>::type> >
ResultType vector_comprehension(const std::vector<T>& in_vec,
Function func) {
ResultType result;
for (auto& elem : in_vec) {
result.push_back(func(elem));
}
return result;
}
template <typename T>
struct Get: T {};
// Macros apparently don't like C++11 style literals unless wrapped in something (in G++ at least).
// So you can't do VFOR({1,2,3}, x, x * x), you have to do
#define VFOR(coll, var, expr) \
vector_comprehension<Get<std::remove_reference<decltype(coll)>::type>::value_type> \
((coll), [&](Get<std::remove_reference<decltype(coll)>::type>::const_reference var) { return (expr);})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment