C++ map和hash_map简单对比

来源:互联网 发布:凯佰赫战盾数据 编辑:程序博客网 时间:2024/06/06 12:52
C++ map 和 hash_map 对比
map的基本数据结构是平衡二叉树,hash_map的基础数据结构是hash_table哈希表,下面程序展示了向map和hash_map中插入数据消耗时间对比。
数据量较小的时候可以选择map,数据量大、对插入查找效率要求高的时候选择hash_map。

/*************************************************************************
    > File Name: map.cpp
    > Author: chenhui
    > Mail: ********* 
    > Created Time: 2017年12月21日 17:23:34
 ************************************************************************/
#include <iostream>
#include <stdio.h>
#include <map>
#include "../Includes/times.h"
#ifdef __GNUC__
#include <ext/hash_map>
#else
#include <hash_map>
#endif


namespace std
{
using namespace __gnu_cxx;
}


using namespace std;


typedef hash_map<int,int> HASHMAPINT2INT;
typedef map<int,int> MAPINT2INT;


int main()
{


MAPINT2INT mapTest;
int64_t timeBegin = getTimeMsec();
for(int i=0;i<5000000;i++)
{
mapTest[i]=i;
}
int64_t timeEnd = getTimeMsec();
printf("map use time:%d\n",timeEnd-timeBegin);


HASHMAPINT2INT hamp;
timeBegin = getTimeMsec();
for(int i=0;i<5000000;i++)
{
hamp[i]=i;
}
timeEnd = getTimeMsec();
printf("hashmap use time:%d\n",timeEnd-timeBegin);
return 0;

}


下面是在自己机器上运行的结果:

map use time:4972
hashmap use time:1214


原创粉丝点击