c++ - 为什么要将 operator< 定义为非成员?

标签 c++ dictionary hashmap

我对 hash_map 做了一些测试,使用 struct 作为键。我定义结构:

struct ST
{

    bool operator<(const ST &rfs)
    {
        return this->sk < rfs.sk;
    }

    int sk;
};

和:

size_t hash_value(const ST& _Keyval)
{   // hash _Keyval to size_t value one-to-one
    return ((size_t)_Keyval.sk ^ _HASH_SEED);
}

然后:

stdext::hash_map<ST, int> map;
ST st;
map.insert(std::make_pair<ST, int>(st, 3));

它给了我一个编译器错误:binary '<' : no operator found which takes a left-hand operand of type 'const ST' (or there are no acceptable conversion)

所以我将运营商改为非成员(member):

bool operator<(const ST& lfs, const ST& rfs)
{
    return lfs.sk < rfs.sk;
}

没关系,所以我想知道为什么?

最佳答案

你错过了一个const:

bool operator<(const ST &rfs) const
{
    return this->sk < rfs.sk;
}

关于c++ - 为什么要将 operator< 定义为非成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16514505/

相关文章:

c++ - 计算大于 400mb 的大文件的 sha-1 或 CRC32 校验和

c# - 如何在 C# 中使用 Dapper 将对象放入字典中?

java - 自定义对象如何存储在HashMap中

java - ReplaceAll、正则表达式和 HashMap 返回 NullPointerException

java - 从列表中删除另一个列表中不存在的所有对象

C++游戏。编译时的错误代码。错误 LNK2019

java - 尝试将 dll 注入(inject)已运行的 JVM?

c++ - 鼠标到射线 - 球体碰撞检测

Python - 类型错误 : 'int' object is not iterable for dictionaries

python - 遍历字典以创建列表