【问题标题】:List iterator as an unordered-map key将迭代器列为无序映射键
【发布时间】:2021-03-23 19:02:59
【问题描述】:
#include <bits/stdc++.h>

int main ()
{
    std::unordered_map<std::list<int>::iterator, int> map;

    return 0;
}

此代码无法编译。错误:

error: no match for call to ‘(const std::hash<std::_List_iterator<int> >) (const std::_List_iterator<int>&)’
  noexcept(declval<const _Hash&>()(declval<const _Key&>()))>

我假设由于某种原因我不能使用列表迭代器作为映射键,但是有什么方法可以让它工作吗?我可以将我的设计更改为不需要,但我更喜欢将列表迭代器作为映射键。

【问题讨论】:

  • 列表迭代器没有定义散列函数(从错误消息中可以看出)。因此,您应该提供自己的自定义哈希函数。我想这会奏效,虽然有点奇怪。
  • 如果你想解决这个错误,你需要为你的密钥类型专门化 std::hash 类。

标签: c++ list iterator key unordered-map


【解决方案1】:

您需要定义如何为std::List&lt;int&gt;::iterator 生成哈希。您可以通过专门针对此类型的 std::hash 模板结构来做到这一点。这是一个幼稚的实现:

namespace std
{
    template<> struct hash<std::list<int>::iterator>
    {
        std::size_t operator()(std::list<int>::iterator const& iter) const noexcept
        {
            return  (std::size_t)&(*iter);
        }
    };
} 

一个好处是它避免了碰撞。

此外,这是允许您在 std 命名空间内定义结构的少数实例之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2014-02-19
    • 2021-04-15
    • 2011-07-31
    • 2010-11-29
    • 2017-07-24
    相关资源
    最近更新 更多