繁体   English   中英

在Stl中查找键Hash_map

[英]Find Key in Stl Hash_map

我是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是否适合我,如果可以,可以给我一些教程。 谢谢你的帮助

您可能会看到: http : //msdn.microsoft.com/zh-cn/library/525kffzd(VS.71).aspx

我认为stdext::hash_compare< int, eqstr >引起了这里的问题。 尝试擦除它。

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

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

您需要考虑的第一件事是您真正需要做的事情以及您真正需要多少性能,然后确定现成的东西是否可以满足要求或者您是否需要编写自己的东西。

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

如果您删除元素是因为它不足以“清空”该条目,则这将导致编写自己的问题,因为另一条目可能会在碰撞过程中跨过您的条目,而现在,如果您放弃它就会放弃到达空值后立即显示为“未找到”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM