C++ map和hash_map簡單對比
阿新 • • 發佈:2019-02-05
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的基本資料結構是平衡二叉樹,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