【发布时间】: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 是否适合我,如果适合,可以给我一些关于它的教程。 感谢您的帮助
【问题讨论】: