Check if Range Contains Value or Subrange in C++23

Check if Range Contains Value or Subrange in C++23

Determining whether a dataset contains a particular value or subrange is a common task in software development. Traditionally, this kind of check required manual iteration with loops or the use of std::find and similar algorithms, which often results in more complex and less maintainable implementations.

Since C++23, the standard std::ranges library provides the contains and contains_subrange functions, offering a straightforward way to check for the presence of value or subrange in a range.

The following example demonstrates how to use these functions to inspect individual values and subranges within a vector:

#include <iostream>
#include <algorithm>
#include <vector>

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

    bool has2 = std::ranges::contains(data, 2);
    bool has7 = std::ranges::contains(data, 7);
    std::cout << has2 << " " << has7 << std::endl; // 1 0

    std::vector sub1 = {3, 4};
    std::vector sub2 = {4, 2};

    bool hasSub1 = std::ranges::contains_subrange(data, sub1);
    bool hasSub2 = std::ranges::contains_subrange(data, sub2);
    std::cout << hasSub1 << " " << hasSub2 << std::endl; // 1 0

    return 0;
}

In this example, contains determines the presence of individual elements, while contains_subrange verifies whether a sequence of elements appears consecutively. Both approaches produce boolean results.

Leave a Comment

Cancel reply

Your email address will not be published.