向unordered_map提供自定义哈希/平等功能

发布于 2025-02-01 10:57:48 字数 699 浏览 1 评论 0原文

我有以下代码:

typedef std::size_t (*hash_func)(const sp_movie& movie);
typedef bool (*equal_func)(const sp_movie& m1,const sp_movie& m2);

typedef std::unordered_map<sp_movie, double, hash_func, equal_func> rank_map;

这些是我要在unordered_map中使用的实际功能:

std::size_t sp_movie_hash(const sp_movie& movie);
bool sp_movie_equal(const sp_movie& m1,const sp_movie& m2);

但是,我无法使用自定义哈希函数和相等的功能创建rank_map。 我不想使用哈希和平等的类来进行,我只想传递到unordered_map我所做的功能。

我尝试了此代码:

rank_map check (sp_movie, double, sp_movie_hash, sp_movie_equal);
rank_map check (sp_movie_hash, sp_movie_equal);

他们两个都没有起作用

I have this following code:

typedef std::size_t (*hash_func)(const sp_movie& movie);
typedef bool (*equal_func)(const sp_movie& m1,const sp_movie& m2);

typedef std::unordered_map<sp_movie, double, hash_func, equal_func> rank_map;

These are my actual functions I want to use in my unordered_map:

std::size_t sp_movie_hash(const sp_movie& movie);
bool sp_movie_equal(const sp_movie& m1,const sp_movie& m2);

How ever, I can't create a rank_map with my custom hash function and equal function I made.
I don't want to do it using classes for hash and equal, I just want to pass to the unordered_map the functions I've made.

I tried this code:

rank_map check (sp_movie, double, sp_movie_hash, sp_movie_equal);
rank_map check (sp_movie_hash, sp_movie_equal);

both of them didn't work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叫嚣ゝ 2025-02-08 10:57:48

唯一合适的构造函数是也接受bucket_count的构造函数。传递0似乎有效:

rank_map check(0, sp_movie_hash, sp_movie_equal);

但是,如果您不想在运行时选择哈希/等式函数,则应将它们变成函数(默认可构造类)。如果您不想自己编写课程,则可以将功能(令人惊讶)包装在std :: Integral_constant

using rank_map = std::unordered_map<sp_movie, double,
    std::integral_constant<decltype(&sp_movie_hash), sp_movie_hash>,
    std::integral_constant<decltype(&sp_movie_equal), sp_movie_equal>
>;

这使您的哈希地图默认构造可构造,并删除存储函数Pointers的开销。

The only suitable constructor is the one that also accepts bucket_count. Passing 0 seems to work:

rank_map check(0, sp_movie_hash, sp_movie_equal);

However, if you don't want to select the hash/equality functions at runtime, you should make them into functors (default-constructible classes). If you don't want to write the classes yourself, you can wrap the functions (surprisingly) in std::integral_constant:

using rank_map = std::unordered_map<sp_movie, double,
    std::integral_constant<decltype(&sp_movie_hash), sp_movie_hash>,
    std::integral_constant<decltype(&sp_movie_equal), sp_movie_equal>
>;

This makes your hash maps default-constructible, and removes the overhead of storing function pointers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文