c++ - 无法比较两个范围

标签 c++ c++20

无法弄清楚为什么下面代码中的 std::ranges::equal 无法编译:

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);
}

MSVC 的编译器错误是:

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

最佳答案

问题 1:A没有可比性,所以你不能用 std::ranges::equal 来比较它使用默认谓词。解决方案:

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

问题 2:您的转换函数产生 std::pair<int, A>这与 map 的元素不匹配 std::pair<const int, A> .解决方案:使用std::pair<const int, A> (或者只是 Map::value_type,这样出错的空间就更少了)。

关于c++ - 无法比较两个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69096279/

相关文章:

c++ - 函数模板接受并返回不同的 lambda

c++ - 为什么我不能在 c++20 中的 istream_view 之后使用 take()

c++ - 立即函数作为 Clang++ 中的默认函数参数初始值设定项

c++ - 尝试使用 QDatastream 序列化自定义类的 QList 时出现错误 C2679

c++ - 这是有效的内存对齐吗?如果没有,应该如何解决?

c++ - 这些 C++ 函数返回什么? ClassA*& func1()

c++ - 将模板函数作为参数传递给另一个函数

c++ - 如何打包python模块依赖的共享对象?

头文件 LNK2019 中的 C++ API 实现

c++ - 在值列表上递归地包含头文件