Generate Repeated Elements with views::repeat in C++23

Generate Repeated Elements with views::repeat in C++23

Creating sequences where the same value appears multiple times is a common need in many programs. Repeating elements manually often requires loops or temporary containers, which can make code more verbose and harder to read.

Since C++23, the standard std::ranges library includes the std::views::repeat adaptor, which provides a simple way to produce repeated values in a range. It can generate either a finite or an infinite sequence, depending on how it is used.

The following example demonstrates how views::repeat can be employed to create a sequence where a string is repeated multiple times:

#include <iostream>
#include <ranges>

int main() {
    std::string s = "Hi";

    for (const auto &val: std::views::repeat(s, 3)) {
        std::cout << val << " "; // Hi Hi Hi
    }
    for (const auto &val: std::views::repeat(s) | std::views::take(3)) {
        std::cout << val << " "; // Hi Hi Hi
    }

    return 0;
}

In the first loop, the two-argument form of views::repeat is used, where the value and the number of repetitions are specified. This creates a range with that many elements, all holding the same value.

The second loop shows the single-argument version of views::repeat, which generates an unbounded range of identical elements. The views::take adaptor is applied to limit the output to the first few repetitions, preventing an infinite loop.

Leave a Comment

Cancel reply

Your email address will not be published.