Skip to content

Instantly share code, notes, and snippets.

@pesterie
Created March 10, 2012 17:22
Show Gist options
  • Save pesterie/2012195 to your computer and use it in GitHub Desktop.
Save pesterie/2012195 to your computer and use it in GitHub Desktop.
unroll
#include <vector>
#include <iostream>
#include <algorithm>
template<int N>
struct unroll
{
template<class InputIterator, class OutputIterator, class Op>
inline static OutputIterator
apply( InputIterator& i, OutputIterator o, Op f)
{
*o++ = f(*i++);
return unroll<N-1>::apply(i,o,f);
}
};
template<>
struct unroll<1>
{
template<class InputIterator, class OutputIterator, class Op>
inline static OutputIterator
apply( InputIterator& i, OutputIterator& o, Op f)
{
*o++ = f(*i++);
return o;
}
};
template<int N, class InputIterator, class OutputIterator, class Op>
OutputIterator unroll_transform( InputIterator b, InputIterator e
, OutputIterator o, Op f)
{
while(b != e)
{
o = unroll<N>::apply(b,o,f);
}
return o;
}
struct op_
{
op_(){};
int operator()(int i) { return i*i; }
};
int main()
{
std::vector<int> first;
std::vector<int> second;
std::vector<int>::iterator it,out;
op_ f;
// set some values:
for(int i=0; i<16; i++) first.push_back(i*10); // first: 10 20 30 40 50
second.resize(first.size()); // allocate space
std::cout << "Unroll\n";
out = unroll_transform<2>(first.begin(), first.end(), second.end(), f);
//for(it=second.begin(); it!=second.end(); ++it)
// std::cout << " " << *it;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment