public
Created

Possible solution for SO question #13541243

  • Download Gist
vectors.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.