Can't compare two ranges

Viewed 75

Can't figure out why std::ranges::equal in the code below does not compile:

struct A { int x; };

using Map = std::map<int, A>;

void some_func()
{
    std::vector<A> v{ {0}, {1}, {2}, {3} };
    
    auto v2m = [](const A& a) { return std::pair<int, A>(a.x, a); };

    const auto actual = std::ranges::single_view(v[2]) | std::views::transform(v2m);

    Map expected{ {v[2].x, v[2]} };

    //Does not compile.
    bool equals = std::ranges::equal(actual, expected);
}

The compiler errors with MSVC are:

error C2672: 'operator __surrogate_func': no matching overloaded function found
error C7602: 'std::ranges::_Equal_fn::operator ()': the associated constraints are not satisfied
1 Answers

Problem 1: A isn't comparable, so you cannot compare it using std::ranges::equal with the default predicate. Solution:

struct A {
    int x;
    friend auto operator<=>(const A&, const A&) = default;
};

Problem 2: Your transform function produces std::pair<int, A> which doesn't match with the elements of map which are std::pair<const int, A>. Solution: use std::pair<const int, A> (or just Map::value_type so that there's less room for mistakes).

Related