Skip to content

Instantly share code, notes, and snippets.

@arizenelm
Created April 6, 2024 15:12
Show Gist options
  • Select an option

  • Save arizenelm/16eab6ee9d5f072f98f9e674a4768c20 to your computer and use it in GitHub Desktop.

Select an option

Save arizenelm/16eab6ee9d5f072f98f9e674a4768c20 to your computer and use it in GitHub Desktop.
C++20 get_chunks()
template<random_access_range range_type>
auto get_chunks(range_type rng, int n_chunks)
{
using begin_t = decltype(ranges::begin(rng));
using end_t = decltype(ranges::end(rng));
using chunk_t = subrange<begin_t, end_t>;
vector<chunk_t> chunks(n_chunks);
size_t offset = 0;
size_t container_size = rng.end() - rng.begin();
size_t count = container_size / n_chunks + container_size % n_chunks;
chunks[0] = chunk_t(rng.begin(), rng.begin() + count);
offset += count;
count = container_size / n_chunks;
for (size_t i = 1; i < n_chunks; i++)
{
chunks[i] = chunk_t{rng.begin() + offset, rng.begin() + offset + count};
offset += count;
}
return chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment