Skip to content

Instantly share code, notes, and snippets.

@DCoderLT
Created November 24, 2012 13:22
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 DCoderLT/4139671 to your computer and use it in GitHub Desktop.
Save DCoderLT/4139671 to your computer and use it in GitHub Desktop.
Possible solution for SO question #13541243
#include <vector>
#include <numeric>
#include <functional>
template<typename T>
std::vector<T> compact(const std::vector<T> &input, int stride, std::function<T(T, T)> op) {
std::vector<T> output(stride);
unsigned int index = 0;
return std::accumulate(input.begin(), input.end(), output, [&index, stride, op](std::vector<T> &acc, T elem) -> std::vector<T> {
acc[index % stride] = op(acc[index % stride], elem);
++index;
return acc;
});
}
int main(int argc, char* argv[])
{
std::vector<int> input;
for(unsigned int i = 1; i < 11; ++i) {
input.push_back(i);
}
auto output = compact(input, 3, std::function<int(int, int)>([](int l, int r) {
return l + r;
}));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment