在C ++中创建迭代器的哈希表

时间:2013-06-24 18:12:55

标签: c++ hash c++11 iterator

我正在尝试通过散列一些节点指针来加速特定的链表操作。这是我正在使用的代码:

unordered_set< typename list< int >::iterator > myhashset;

在Visual Studio 2012中,我收到“错误C2338:C ++标准不提供此类型的哈希”,因为编译器不知道如何散列迭代器。因此,我需要为列表迭代器实现我自己的哈希函数,如:

struct X{int i,j,k;};

struct hash_X{
  size_t operator()(const X &x) const{
    return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
  }
};

wikipedia reference

我无法弄清楚迭代器的哪些成员保证唯一性(因此,我想要哈希的成员)。另一个问题是那些成员可能是私人的。

我想到的一个解决方案是重新实现和list :: iterator,但这看起来像是一个黑客,并引入了更多代码来维护。

2 个答案:

答案 0 :(得分:6)

使用迭代器引用的元素的地址。

struct list_iterator_hash {
    size_t operator()(const list<int>::iterator &i) const {
        return hash<int*>(&*i);
    }
};

但这仅适用于可解除引用的迭代器,而不适用于end()list<int>::iterator()

答案 1 :(得分:0)

您可以使用指向元素的指针来代替迭代器。假设您有一个结构列表MyStruct。您可以使用

unordered_set<MyStruct*> myhashset;

,并且C ++标准库已经实现了std::hash for any pointer

因此,如果您需要插入或搜索listIt,请使用&(*listIt),它将获得类型为MyStruct*的指针。