llvm / llvm/llvm-project

[clang-tidy] Add a check to replace boolean search idioms with `std::ranges::contains` / `std::ranges::contains_subrange`

Open
#189,663 2 comments 0 reactions 0 assignees View on GitHub
check-request clang-tidy
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

clang-tidy already has checks that modernize iterator-based algorithm calls into ranges-based ones, but it would still be useful to have a check for the next step up: canonical boolean search idioms that are really spelling `std::ranges::contains` or `std::ranges::contains_subrange`.

Today code like this is common:

```cpp
auto found = std::find(v.begin(), v.end(), x) != v.end();
```

or:

```cpp
if (std::ranges::find(r, x) != std::ranges::end(r)) {
...
}
```

and substring/subrange tests are often written as:

```cpp
auto has_sub = std::search(r.begin(), r.end(), sub.begin(), sub.end()) != r.end();
```

In C++23 the intent can be expressed more directly as:

```cpp
auto found = std::ranges::contains(v, x);
```

and:

```cpp
auto has_sub = std::ranges::contains_subrange(r, sub);
```

These spellings are shorter and clearer, and they make the boolean nature of the test explicit rather than encoding it indirectly through comparison against an end iterator.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.