如何在C ++中使用std :: unordered

编程入门 行业动态 更新时间:2024-10-08 18:36:57
本文介绍了如何在C ++中使用std :: unordered_set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我选择了Java中的哈希表的概念,所以我意识到,对于用于定制类的通用哈希集合容器,必须为散列函数和相应的相等函数提供定义。

在Java中,这意味着重写方法

int hashCode()

boolean equals(Object o)

。 接受5个模板参数(你能相信吗?),它看起来像一个怪物,并让我的头旋转。

感谢它,如果可以给出一个简单的例子,当前的玩具类:

class一些{ public: int a; };

其中hash函数只返回a的值,并且相等测试函数返回true iff成员'a'的值是相同的。

谢谢

解决方案

步骤1:为您的类型重载 operator == :

bool operator ==(const Some& x,const Some& y) { return xa == ya; $ / code>

第二步:专用 std :: hash $ b

namespace std { template<> code> struct hash< Some> { typedef一些argument_type; typedef size_t result_type; size_t operator()(const Some& x)const { return x.a; } }; }

第3步:简单测试:

int main() { std :: unordered_set< Some>测试; test.insert(一些{42}); }

第四步:获利!

I picked the concepts of hash tables in Java, so I was aware that for a generic "hash set" container to work for custom classes, one must provide definition for a hash function and an corresponding equality function.

In Java, this would mean overriding method

int hashCode()

and

boolean equals (Object o)

.

I was expecting the same logic in c++'s STL, but was having trouble understanding the syntax. Specifically, std::unordered_set<> accepts 5 template arguments (can you believe that?), which looks like a monster and makes my head spin.

So I would be appreciate it if one could give a simple example for the current toy class:

class Some{ public : int a; };

Of which the hash function simply returns the value of a, and the equality test functions returns true iff the values of member 'a' are the same.

Thanks

解决方案

Step 1: Overload operator== for your type:

bool operator==(const Some& x, const Some& y) { return x.a == y.a; }

Step 2: Specialize std::hash for your type:

namespace std { template<> struct hash<Some> { typedef Some argument_type; typedef size_t result_type; size_t operator()(const Some& x) const { return x.a; } }; }

Step 3: A simple test:

int main() { std::unordered_set<Some> test; test.insert(Some{42}); }

Step 4: Profit!

更多推荐

如何在C ++中使用std :: unordered

本文发布于:2023-11-29 01:53:30,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   std   unordered

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!