You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++自定义类型作为std::map键引发error C2784的原因咨询

关于error C2784错误的原因与解决方法

错误根源

你遇到的C2784错误本质原因是:std::map作为有序容器,要求键类型必须支持小于比较操作,但你自定义的Vector2i结构体没有重载operator<。编译器在尝试寻找合适的比较运算符时,错误匹配到了std::nullptr_t与std::shared_ptr的operator<重载,从而抛出了模板参数推导失败的错误信息(这个错误信息有一定误导性,核心问题还是键类型的比较逻辑缺失)。

解决方案

有两种常用的解决方式:

方式一:给Vector2i重载operator<

直接在结构体中定义小于比较逻辑,比如按x优先、再按y比较:

struct Vector2i
{
    int x;
    int y;

    // 重载operator<,定义比较规则
    bool operator<(const Vector2i& other) const
    {
        if (x != other.x)
            return x < other.x;
        return y < other.y;
    }
};

// 后续代码可正常使用
std::map<Vector2i, Chunk*> map{};
map.insert({ Vector2i{0,0}, nullptr });

方式二:自定义比较器作为std::map的模板参数

如果不想修改Vector2i结构体,可以定义独立的比较器,作为std::map的第三个模板参数:

struct Vector2i
{
    int x;
    int y;
};

// 自定义比较器
struct CompareVector2i
{
    bool operator()(const Vector2i& a, const Vector2i& b) const
    {
        if (a.x != b.x)
            return a.x < b.x;
        return a.y < b.y;
    }
};

// 使用自定义比较器声明map
std::map<Vector2i, Chunk*, CompareVector2i> map{};
map.insert({ Vector2i{0,0}, nullptr });

内容的提问来源于stack exchange,提问作者zeke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:10:28