c++ - 在 STL Hash_map 中查找键

标签 c++ stl hashmap

我是 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/en-us/library/525kffzd(VS.71).aspx

我认为stdext::hash_compare< int, eqstr >造成这里的问题。尝试删除它。

HashMap 的另一种实现是std::tr1::unordered_map .但我认为各种 HashMap 实现的性能是相似的。您能否详细说明 boost::unordered_map 有多慢?你是怎么用的?有什么用?

关于c++ - 在 STL Hash_map 中查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4407193/

相关文章:

c++ - 尽管使用了 setwindowpos,为什么窗口没有出现在顶部?

c++ - 没有从等式中得到正确的答案。还有,无限循环

c++ - 即使我没有使用引用,值(value)也会改变

go - 按顺序收集值,每个值都包含一个映射

java - 在 Java 中反转嵌套的 TreeMap

C++ nullptr 成员对象导致 DLL 共享库中的 "Unable To Read Memory"

c++ - map<..,..> 的第二部分是否稳定?

c++ - 简单链表与 STL::list。哪个最好?

c++ - 为什么 std::set 中的项目不能为 'popped' ?

javascript - 在 JavaScript 中使用元素作为哈希的键