如何为自定义结构中定义的无序集编写自定义哈希函数?

问题描述 投票:1回答:1

我正在尝试为自己的结构编写一个新的哈希函数。这是我的代码:

struct people{
    int id;
    unordered_set<people>friends;
    people(int x) : id(x) {}
};

我需要为朋友们提供哈希函数,例如:

struct peopleHash{
    size_t operator()(const people& p) const{
        return p.id;
    }
}

问题出在这里:如果我首先初始化人员,那么peopleHash函数会找到“未定义类型的人”。如果我首先初始化peopleHash,也会发生同样的事情。我试图在people结构中定义peopleHash,例如:

struct people{
    int id;
    struct peopleHash{
        size_t operator()(const people& p) const{
            return p.id;
        }
    };
    unordered_set<people, peopleHash>friends;
    people(int x) : id(x) {}
};

但编译说:

error: invalid operands to binary expression ('const people' and 'const people')
        {return __x == __y;}

我不知道如何处理这个......有什么帮助吗?

c++ c++11 hash unordered-set
1个回答
1
投票

你不能这样做。当您实例化未定义行为的people时,std::unordered_set将是一个不完整的类型。见http://eel.is/c++draft/library#res.on.functions

© www.soinside.com 2019 - 2024. All rights reserved.