【问题标题】:Find Key in Stl Hash_map在 Stl Hash_map 中查找键
【发布时间】:2011-05-23 08:58:12
【问题描述】:

我是 C++ 初学者,对哈希表有一些问题。我的程序需要一个哈希表结构。首先我使用 boost unordered_map。它拥有我需要的所有东西,但它使我的程序如此缓慢。然后我想测试 stl hash_map,但我不能做我需要的所有事情。这是我的第一个代码(这是示例)

#include <hash_map>
using namespace std;

struct eqstr
{
  bool operator()(int s1, int s2) const
  {
    return s1==s2;
  }
};
typedef stdext::hash_map< int, int, stdext::hash_compare< int, eqstr > > HashTable;

int main()
{
  HashTable a;
  a.insert( std::pair<int,int>( 1, 1 ) );
  a.insert( std::pair<int,int>( 2, 2 ) );
  a.insert( std::pair<int,int>( 4, 4 ) );
//next i want to change value of key 2 to 20
  a[2] =  20;
//this code only insert pair<2,20> into a, buy when I use boost unordered_map this code                         modify previous key of 2  
//next I try this code for delete 2 and insert new one
  a.erase(2);//this code does work nothing !!!
//next I try to find 2 and delete it
  HashTable::iterator i;
  i = a.find(2);//this code return end, and does not work!!!
  a.erase(i);//cause error
//but when I write this code, it works!!!
  i=a.begin();
  a.erase(i);
//and finally i write this code
  for (i = a.begin(); i!=a.end(); ++i)
  {
    if (i->first == 2 )
      break;
  }
  if (i!= a.end())
    a.erase(i);
//and this code work 

但是如果我想搜索我的数据,我使用数组而不是 hash_map,为什么我不能使用 o(1) 从 hash_map 访问、修改和删除 我的错误是什么,哪个哈希结构对我的程序来说是快速的,在初始化阶段有很多值修改。 google sparse_hash 是否适合我,如果适合,可以给我一些关于它的教程。 感谢您的帮助

【问题讨论】:

    标签: c++ stl hashmap


    【解决方案1】:

    你可以看看:http://msdn.microsoft.com/en-us/library/525kffzd(VS.71).aspx

    我认为stdext::hash_compare&lt; int, eqstr &gt; 造成了这里的问题。尝试删除它。

    哈希映射的另一个实现是std::tr1::unordered_map。但我认为各种哈希映射实现的性能是相似的。您能否详细说明 boost::unordered_map 有多慢?你是如何使用它的?干什么用的?

    【讨论】:

    • 这是正确答案。 hash_compare 函数对象用于确定元素的相对顺序。我将 mina 的代码从 s1==s2 更改为 s1&lt;s2,这解决了问题。当然,less&lt;key&gt; 是默认值,因此不指定 hash_compare 函数也可以纠正 mina 的问题。
    【解决方案2】:

    哈希映射种类繁多,许多开发人员仍在编写自己的哈希映射,因为与通用映射相比,根据自己的特定用途编写的哈希映射通常可以获得更高的性能,当人们想要真正的高性能时,他们倾向于使用哈希。

    首先你需要考虑的是你真正需要做什么以及你真正需要多少性能,然后确定现成的东西是否可以满足,或者你是否需要自己编写一些东西。

    如果您从不删除元素,例如,只写一次然后不断查找,那么您可以经常重新哈希以减少您获得的实际集合的冲突:设置时间更长但查找速度更快。

    如果您删除元素,则在编写您自己的元素时会出现问题,因为将条目“归零”是不够的,因为另一个元素可能在其碰撞过程中越过了您的元素,现在如果您查看它一旦达到您的空值,就会放弃“未找到”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多