C++中设置无序,为什么需要哈希

Unordered set in C++, why is hash needed?

本文关键字:哈希 为什么 设置 无序 C++      更新时间:2023-10-16

我只想在一个无序集合中存储几个对象。创建几组,

auto set1 = std::unordered_set<Myclass>();

我有时会收到这样的错误,很多:

未定义模板"std::__1::哈希"的隐式实例化

除了开箱即用的unordered_set之外,没有其他选择吗?为什么需要"哈希"?

std::unordered_set通过对您使用的键进行哈希处理来索引其存储中的值,这与哈希表或C++ std::unordered_map实现非常相似。

如果您不想为 Myclass 编写哈希函数,只需改用 std::set 即可。这可能比定义哈希函数并使用std::unordered_set 的性能更差,但如果编写哈希函数对您的类来说很困难,则可能是值得的。取决于类和应用程序。

如果要使用std::unordered_set,则需要为Myclass提供一个哈希函数。要么为您的类提供std::hash专用化,要么提供哈希策略以std::unordered_set .

//specialize std::hash
namespace std
{
    template<>
    struct hash<Myclass>
    {
        typedef Myclass argument_type;
        typedef std::size_t result_type;
        result_type operator()(argument_type const& s) const
        {
            //some code to hash a Myclass object
        }
    };
}
auto set1 = std::unordered_set<Myclass>();   
//hashing policy version
class MyclassHash
{
public:
    std::size_t operator()(Myclass const& s) const 
    {
        //some code to hash a Myclass object
    }
};
auto set1 = std::unordered_set<Myclass, MyclassHash>();