Skip to content

Instantly share code, notes, and snippets.

@marcinwol
Created July 1, 2015 06:25
Show Gist options
  • Save marcinwol/701f7c83b649812ac9fb to your computer and use it in GitHub Desktop.
Save marcinwol/701f7c83b649812ac9fb to your computer and use it in GitHub Desktop.
C++11: devide vector into k-sized chunks
/**
* Code taken from http://stackoverflow.com/a/11408470/248823
*/
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <iostream>
#include <stdexcept>
#include <algorithm>
template <
typename Container,
typename OutIter,
typename ChunkSepFunctor
>
OutIter chunker(
Container const& c,
typename Container::size_type const& k,
OutIter o,
ChunkSepFunctor sep
)
{
using namespace std;
if (k <= 0)
throw domain_error("chunker() requires k > 0");
auto chunkBeg = begin(c);
for (auto left=c.size(); left != 0; )
{
auto const skip = min(left,k);
o = copy_n(chunkBeg, skip, o);
left -= skip;
advance(chunkBeg, skip);
if (left != 0)
sep();
}
return o;
}
int main()
{
using namespace std;
using VECTOR = vector<string>;
VECTOR v{"a","b","c","d","e"};
for (VECTOR::size_type k = 1; k < 7; ++k)
{
cout << "\n\nk = " << k << "..." << endl;
chunker(
v, k,
ostream_iterator<VECTOR::value_type>(cout),
[]() { cout << endl; }
);
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment