h);
? ? ? ? }
};
?
?
void curTime()
{
? ? ? ? time_t aTime = time(NULL);
? ? ? ? struct tm * curtime = localtime(&aTime);
? ? ? ? char ctemp[20];
? ? ? ? strftime(ctemp, 20, "%Y-%m-%d %H:%M:%S" , curtime);
? ? ? ? cout<}
?
int main()
{
? ? ? ? __gnu_cxx::hash_map fileMap;
? ? ? ? string temp;
? ? ? ? int i = 0;
? ? ? ? ifstream in;
? ? ? ? in.open("/tmp/name.txt", ifstream::in);
? ? ? ? if (!in)
? ? ? ? {
? ? ? ? ? ? ? ? cout << "open file failed" << endl;
? ? ? ? ? ? ? ? return 1;
? ? ? ? }
? ? ? ? curTime();
? ? ? ? while (in >> temp)
? ? ? ? {
? ? ? ? ? ? ? ? if (fileMap.find(temp) == fileMap.end())
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ++i;
? ? ? ? ? ? ? ? ? ? ? ? fileMap[temp] = i;
? ? ? ? ? ? ? ? }
? ? ? ? }
? ? ? ? curTime();
? ? ? ? cout << i << endl;
? ? ? ? in.close();
? ? ? ? return 0;
}
#编译
[linuxidc@localhost ~]$ g++ -Wno-deprecated 4.cpp -o strhashMap
3.STL的map
#include
#include
#include
#include
1
2 #编译
[linuxidc@localhost ~]$ g++ 2.cpp -o map
4.执行查看结果
[linuxidc@localhost ~]$ ./hashMap? ? ? #7秒
2015-11-06 16:25:41
2015-11-06 16:25:48
459256
[linuxidc@localhost ~]$ ./strhashMap? ? #8秒,和上面的相差无几
2015-11-06 16:25:50
2015-11-06 16:25:58
459256
[linuxidc@localhost ~]$ ./map? ? ? ? ? #26秒
2015-11-06 16:26:02
2015-11-06 16:26:28
459256
五、总结
这个测试仅仅是个人娱乐,并没有什么实际价值。最后就是一句话,hash_map是基于hash_table实现的,而hash_table是把以双刃剑,用的好效率很高O(1),用的不好奔着O(N)就去了。
六、注意hash_map死循环
这个问题简单说来,就是gnu的实现是,内部有个_M_Cur指针指示当前位置A,每次计算operator++,都用当前位置的key调用hash函数计算下一个位置B,如果key传入hash_map以后,又在外部将其内容破坏,导致hash函数计算后的B位置在A位置之前,那么从B到达A以后,又会跳回B,形成B-A区间的死循环。
#include
#include
#include
?
using namespace std;
int main()
{
? ? ? ? __gnu_cxx::hash_map hashMap;
? ? ? ? char name[10] = "zhu";
? ? ? ? hashMap.insert(pair(name, 1));
? ? ? ? strncpy(name, "wang", 10);? ? ? //在外部改变了已经传入hash_map中的key,导致死循环
? ? ? ? for (__gnu_cxx::hash_map::iterator it = hashMap.begin(); it != hashMap.end(); ++it)
? ? ? ? {
? ? ? ? ? ? ? ? cout << it->first << "? " << it->second << endl;
? ? ? ? }
? ? ? ? return 0;
}?