在vs中使用hash_map的一个小总结

来源:互联网 发布:中企动力源码下载 编辑:程序博客网 时间:2024/06/14 16:08

一直以来都不是太习惯使用hash_map

在项目中首次使用,本来以为可以像使用vector的遍历操作来调用的,但是……

 

hash_map的原理是使用一个hash函数,来存储key和value

看了一下这里:http://technet.microsoft.com/en-us/office/525kffzd(VS.90).aspx

原来在vs中的hash_map已经被unordered_map取代了

 

这是一个对unordered_map的使用和说明:

http://technet.microsoft.com/en-us/office/bb982522(v=vs.90)

 

 

一段引用别人blog的一段话:

hash_map这个东西,好好理解一下就明白,通过hash把key分布在一个大的空间内。空间内的key分布式相当离散的,要再上面做遍历操作肯定得遍历各个hash bucket(当然,你自己维护一个链表除外),使用遍历器的代价是十分高昂的,而这个begin()也不例外!代码里头也确实这么写的(/usr/include/c++/4.1.1/ext/hashtable.h):      iterator      begin()      {    for (size_type __n = 0; __n < _M_buckets.size(); ++__n)      if (_M_buckets[__n])        return iterator(_M_buckets[__n], this);    return end();      }所以,使用hash_map的时候一定要尽量避开iterator。


可以看出来我也进入了一个误区,用了iterator,也可能我对find不熟引起的,可以看下面的一段测试代码:

#include "stdafx.h"#include "iostream"#include "fstream"#include "string"#include "sstream"using namespace std;#include "unordered_map"#include "time.h"#define  BEGINE_GET_TIME clock_t start_time = clock();#define  ENG_GET_TIME    clock_t end_time = clock();#define  CONSOLE_TIME    cout << "Running time is: " << static_cast<double>(end_time - start_time) / CLOCKS_PER_SEC * 1000 << "ms" << endl; //输出运行时间int _tmain(int argc, _TCHAR* argv[]){unordered_map<string, string> test;stringstream ss;string tmp_key;string tmp_value;for (int index = 0; index < 10001; index++){ss << "zeng"; ss << index;ss >> tmp_key;ss.clear();ss << "zengraoli"; ss << index;ss >> tmp_value;ss.clear();test.insert(pair<string, string>(tmp_key, tmp_value));ss.str("");}// BEGINE_GET_TIME;// // 先来看看遍历的速度// for (int count = 0; count < 10000; count++)// {//  unordered_map<string, string>::iterator it;//  for (it = test.begin(); it != test.end(); it++)//  {//  if (it->first == "zeng10000")//  {//  if (it->second == "zengraoli10000")//  {//  //cout << "find" << endl;//  }//  }//  }// }// ENG_GET_TIME;// CONSOLE_TIME;BEGINE_GET_TIME;// 对比下使用find的情况for (int count = 0; count < 10000; count++){unordered_map<string, string>::iterator it;it = test.find("zeng10000");if (it == test.end()){cout << "not find" << endl;}else{if (it->second == "zengraoli10000"){//cout << "find" << endl;}}}ENG_GET_TIME;CONSOLE_TIME;return 0;}


第一个使用迭代器的消耗时间是:



第二个使用find消耗的时间是:



可以看出来,数据量一大的情况小,find更加节省时间

1 0