I would like to use an idiomatic (std::algorithm or similar) version of Scala's .grouped
in C . This breaks a sequence into groups of size N
where the last group may be smaller. Any ideas?
Reference: https://www.scala-lang.org/api/current/scala/collection/Seq.html#grouped(size:Int):Iterator[C]
I've successfully used a loop with std::min
but I would like something built in. This is my solution for grouping into chunks of 7 (found here on SO in another answer):
std::vector<std::vector<uint64_t>> chunked;
std::vector<uint64_t> flat;
// group into chunks of 7
for (size_t i = 0; i < flat.size(); i = 7) {
auto last = std::min(flat.size(), i 7);
std::vector<uint64_t> chunk =std::vector<uint64_t>(flat.begin() i, flat.begin() last);
chunked.emplace_back(chunk);
}
CodePudding user response:
std::ranges::views::chunk would do the job (but is only available "since" C 23).