2014-03-26 57 views
1

我选择了Java中的哈希表的概念,所以我意识到,对于用于自定义类的通用“哈希集合”容器,必须为哈希函数和相应的相等函数提供定义。如何在C++中使用std :: unordered_set?

在Java中,这将意味着压倒一切的方法

int hashCode() 

boolean equals (Object o) 

。我期待在C++的STL中使用相同的逻辑,但是在理解语法时遇到了困难。具体来说,std :: unordered_set <>接受5个模板参数(你能相信吗?),它看起来像一个怪物,并让我的头旋转。

所以我会很感激,如果人们可以举一个简单的例子当前玩具类:

class Some{ 
public : 
int a; 
}; 

其中的哈希函数返回的值,和平等测试功能返回true当且仅当成员'a'的值是相同的。

由于

+0

http://en.cppreference.com/w/cpp/utility/hash – user1520427

+0

'我选择了Java中哈希表的概念[...]我期待着C++ STL中的相同逻辑请记住,Java和C++是不同的语言,需要不同的思维方式。 – fredoverflow

+0

'Key','Hash','KeyEqual'和'Allocator'是4个参数,而不是5个。 – fredoverflow

回答

4

步骤1:过载operator==你的类型:

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

步骤2:专营std::hash你的类型:

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; 
     } 
    }; 
} 

步骤3:一个简单的测试:

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

第4步:获利!

1

我没有编译器,因此有可能是错误的,但它应该是类似于:

namespace std { 
    template <> 
    struct hash<Some> 
    { 
    typedef Some argument_type; 
    typedef std::size_t result_type; 

    result_type operator()(const Some & t) const 
    { 
     return t.a; 
    } 
    }; 
} 
+0

啊,我忘了'argument_type'和'result_type'!谢谢你提醒我。 – fredoverflow

+0

正如我所看到的那样,您正在利用std :: unsorted_set默认情况下查找std :: hash 作为用于计算给定对象之外的哈希值的函数对象的概念。 – Diaz

+0

我做了几乎相同的事情,除了我创建了自己的类(而不是std :: hash <>),并且在声明容器时将其指定为Hasher。编译器抱怨“无效的操作数到二进制表达式”,并且我不知道:( – Diaz

相关问题