【问题标题】:error C2784 c++ std::map with 2 user-defined types具有 2 个用户定义类型的错误 C2784 c++ std::map
【发布时间】:2022-11-01 11:22:51
【问题描述】:

有人可以解释为什么这段代码会产生。无论我将地图值设置为什么,我都能将错误缩小到该段。

C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\xstddef(117,1): 错误 C2784: 'bool std::operator <(std::nullptr_t,const std::shared_ptr<_Ty> &) noexcept': 无法从 'const _Ty' 推导出 'const std::shared_ptr<_Ty> &' 的模板参数

struct Vector2i
{
    int x;
    int y;
};
std::map<Vector2i, Chunk*> map{};
map.insert({ Vector2i{0,0}, nullptr });

谢谢 :)

我尝试注释掉 Vector2i 结构的所有其他实例,并且该段似乎是导致此错误的唯一位置。

【问题讨论】:

  • std::map 使用比较函数对其项目进行排序。如果您不指定默认值是 std::less&lt;key&gt; 其中 key 是您的 Vector2i

标签: c++


【解决方案1】:

std::map 是一个有序容器,因此需要键来提供“小于”运算符进行比较。这可以在映射的模板参数中提供,或者如果您为您的类型定义了operator&lt;,它可以是隐式的。

struct Vector2i
{
    int x;
    int y;

    bool operator<(const Vector2i& other) const {
        return x < other.x || x == other.x && y < other.y;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多