我是C++的初学者,并且有一些哈希表的问题。我的程序需要一个哈希表结构。首先我使用boost unordered_map。它拥有我需要的所有东西,但它使我的程序变得如此缓慢。那么我想测试stl hash_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,为什么我不能访问,modity并与邻距离的hash_map删除(1) 我的错误是什么,以及哪个散列结构对于我的程序来说很快,在初始化阶段有很多值修改。是谷歌sparse_hash适合我,如果是的话,可以给我一些教程。 感谢任何帮助
这是正确的答案。 hash_compare函数对象用于确定元素的__relative顺序___。我把mina的代码从's1 == s2'改为's1'是默认值,所以不指定hash_compare函数也可以纠正mina的问题。 –
Blastfurnace
2010-12-10 16:02:09