Group Adjacent Range Elements with views::chunk_by in C++23

Group Adjacent Range Elements with views::chunk_by in C++23

Organizing sequences of data into meaningful groups is a frequent requirement in many programs. When elements that share a relationship appear next to each other, grouping them manually often requires conditional checks and additional state management inside loops. These methods often result in more verbose code and can reduce readability.

Since C++23, the standard std::ranges library provides the std::views::chunk_by adaptor for partitioning a range into adjacent groups according to a predicate. It produces subranges of adjacent elements that satisfy the specified condition.

The following example demonstrates how views::chunk_by can be used to group neighboring values that are equal inside a vector:

#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector data = {1, 1, 1, 2, 2, 3, 1, 1};

    auto groups = data | std::views::chunk_by([](int a, int b) {
        return a == b;
    });

    for (auto group: groups) {
        std::cout << "[ ";
        for (int v: group) {
            std::cout << v << " ";
        }
        std::cout << "]" << std::endl;
    }

    return 0;
}

Output:

[ 1 1 1 ]
[ 2 2 ]
[ 3 ]
[ 1 1 ]

In this code, the predicate compares neighboring elements and returns true when they are identical. As long as the condition remains satisfied, elements are placed in the same chunk. When the predicate becomes false, a new group begins.

Each produced chunk behaves like a range itself, making it possible to iterate through the grouped elements using a nested loop. This design allows the data to remain in its original container while still providing a convenient grouped view.

Leave a Comment

Cancel reply

Your email address will not be published.