2010-12-10 34 views
0

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

回答

1

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

我觉得stdext::hash_compare< int, eqstr >在这里造成的问题。试着抹去它。

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

+0

这是正确的答案。 hash_compare函数对象用于确定元素的__relative顺序___。我把mina的代码从's1 == s2'改为's1 '是默认值,所以不指定hash_compare函数也可以纠正mina的问题。 – Blastfurnace 2010-12-10 16:02:09

0

哈希映射有很多不同的类型,许多开发人员仍然自己编写,因为您可以在自己的文件中获得更高性能,写入自己的特定用途,而不是通用文件,当人们想要非常高的性能时,他们倾向于使用散列。

您首先需要考虑的是您真正需要做的事情以及您真正需要的性能,然后确定现成的设备是否能够满足要求,或者您是否需要自己写一些。

例如,如果您从不删除元素,例如只编写一次然后不断查找,那么您通常可以重新调整以减少您获得的实际集合的冲突:在安装时更长,但查找时更快。

如果您删除元素,将会发生编写问题的原因,因为它不足以“空”该条目,因为另一个可能已经跨越了您的碰撞过程的一部分,现在如果您看起来那个一旦它达到你的空值,它会放弃为“未找到”。

相关问题