Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compare two ranges

Tags:

c++

c++20

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
like image 653
Dmitriano Avatar asked Jan 22 '26 11:01

Dmitriano


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).

like image 155
eerorika Avatar answered Jan 24 '26 07:01

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!