【问题标题】:Using pair as key for hash_map under Visual Studio在 Visual Studio 下使用 pair 作为 hash_map 的键
【发布时间】:2013-01-30 11:38:05
【问题描述】:

在 Visual Studio 2010 下尝试使用 pair 作为 hash_map 的键值。

无法编译。

int _tmain(int argc, _TCHAR* argv[]) 
{
   hash_map <pair<int, int>, int> months;
    months[pair<int, int>(2,3)] = 1;

   int d;
   cin >> d;

   return 0;
}

收到错误消息:

错误 1 ​​错误 C2440: 'type cast' : 无法从 'const std::pair<_ty1>' 转换为 'size_t' c:\program files\microsoft visual studio 10.0\vc\include\xhash 34 1测试应用程序1

我知道这可能是因为hash_map 没有为pair 提供专业化。有什么简单的方法可以解决吗?

【问题讨论】:

  • 嗯,可以使用 std::map 但不能使用 std::unordered_map
  • “在 Visual Studio 2010 下” - 删除 hash_map 并使用正确的 std::unordered_map。虽然,这仍然不能解决你的问题。不幸的是,缺少 std::pair 的哈希函数是 C++11 中最大的疏忽之一(但好吧,至少他们在 15 年后意识到哈希是有用的数据结构)。

标签: c++ hashmap std-pair


【解决方案1】:

您必须编写自己的 hash_compare - 为您用作键的对象的函数!

你的情况是std::pair&lt;int,int&gt;

看看this 的帖子——也许你会更好地了解实现自己的比较器!

【讨论】:

    【解决方案2】:

    这是一个非常简单的 pair&lt;int,int&gt; 哈希函子示例,它应该为您提供足够的开始来实现自己的:

    using namespace std;
    
    class pair_hasher
    {
    public:
        size_t operator()(const pair<int, int> & p) const
        {
            return p.first*100 + p.second*10000;
        }
    };
    
    typedef unordered_map <pair<int, int>, int, pair_hasher> pair_map;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        pair_map months;
        pair<int, int> p = make_pair<int, int>(2,3);
        months[p] = 1;
        cout << months[p] << endl;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多