Why doesn't std::ranges::find compile while std::find works fine? – C++

by
Ali Hasan
.net-generic-math std-ranges

Quick Fix: Utilize the projection function to project ‘S’ to ‘Sa’ in the ‘stdranges::find’ call. This ensures that the comparison is performed on the desired attribute ‘a’ of ‘S’ rather than the entire ‘S’ object.

The Problem:

In C++ standard library, the std::ranges library provides a set of generic algorithms that operate on ranges of elements, such as vectors, arrays, and lists. These algorithms are designed to be more concise and expressive than the traditional algorithms in the std namespace. However, when trying to use the std::ranges::find algorithm to search for an element in a vector of custom structs, the code does not compile. In contrast, using the traditional std::find algorithm with the same vector and search value compiles and works as expected. The goal is to understand why std::ranges::find does not compile in this specific scenario and what modifications are needed to make it work.

The Solutions:

Solution 1: Using Projection Function

`ranges::find` uses `ranges::equal_to` by default to compare the elements of the range with the value. The call operator of `ranges::equal_to` constrains the two types to satisfy `equality_comparable_with`, which is `S` and `int` in the provided example.

`equality_comparable_with` requires `S` to be comparable with itself and needs to have a common reference with `const int&`, which is not the case in the given code.

To resolve this, use the projection function to project `S` to `S::a` as follows:

if (auto const it{std::ranges::find(iv, 1, &S::a)}; it != iv.end()) {
    std::cout << "Found!\n" << "\n";
}

Q&A

Why does stdfind compile but stdranges::find doesn’t?

stdrangesfind uses ranges::equal_to by default, which requires S to be comparable with itself and have a common reference with const int&

What’s the workaround?

Use the projection function to project S to S::a

Video Explanation:

The following video, titled "”Kelly", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

”Kelly