title: Partitioning/batch/chunk a container into equal sized pieces using std algorithms
body: <p>I came across a situation where I had to batch process a set of records off to a database.  I am wondering how I could accomplish this with <strong>std algorithms</strong>.</p>
  
  <p>Given 10002 records I want partition it into bins of 100 records for processing, with the remainder being a bin of 2.</p>
  
  <p>Hopefully the following code will better illustrate what I'm trying to accomplish.  I'm completely open to solutions involving iterators, lambdas any sort of modern C++ fun.</p>
  
  <pre><code>#include &lt;cassert&gt;
  #include &lt;vector&gt;
  #include &lt;algorithm&gt;
  
  template&lt; typename T &gt;
  std::vector&lt; std::vector&lt; T &gt; &gt; chunk( std::vector&lt;T&gt; const&amp; container, size_t chunk_size )
  {
    return std::vector&lt; std::vector&lt; T &gt; &gt;();
  }
  
  int main()
  {
    int i = 0;
    const size_t test_size = 11;
    std::vector&lt;int&gt; container(test_size);
    std::generate_n( std::begin(container), test_size, [&amp;i](){ return ++i; } );
  
    auto chunks = chunk( container, 3 );
  
    assert( chunks.size() == 4 &amp;&amp; "should be four chunks" );
    assert( chunks[0].size() == 3 &amp;&amp; "first several chunks should have the ideal chunk size" );
    assert( chunks.back().size() == 2 &amp;&amp; "last chunk should have the remaining 2 elements" );
  
    return 0;
  }
  </code></pre>