C++: Split a list into batches with bounded next
A final batch often has fewer elements than the requested size. The three-argument std::ranges::next overload accepts an end bound so a forward traversal stops safely at that boundary.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save as cpp-ranges-next-bounded-batches.cpp:
#include <cassert>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <list>
int main() {
const std::list<int> values{10, 20, 30, 40, 50};
constexpr std::ptrdiff_t batch_size = 2;
static_assert(batch_size > 0);
int batches = 0;
for (auto first = values.begin(); first != values.end();) {
const auto last = std::ranges::next(first, batch_size, values.end());
for (auto it = first; it != last; ++it) std::cout << ' ' << *it;
std::cout << '\n';
first = last;
++batches;
}
assert(batches == 3);
assert(std::ranges::next(values.end(), batch_size, values.end()) == values.end());
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-ranges-next-bounded-batches.cpp -o cpp-ranges-next-bounded-batches &&
./cpp-ranges-next-bounded-batchesObserved output:
10 20
30 40
50How it works
The first two batches each contain two values. The final advance stops after 50 and returns the end iterator. Assigning that iterator to first finishes the outer loop. A positive batch size guarantees progress while elements remain.
Limits and choices
The bound must belong to the same valid range and be reachable in the traversal direction. This overload does not repair an invalid iterator or a dangling container. Advancing through a list is linear in the number of steps; a random-access iterator may support constant-time movement. The source stays unchanged during traversal.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-ranges-next-bounded-batches.cpp cpp-ranges-next-bounded-batches
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.