map 与 unordered_map

时间:2022-06-08 03:03:09

两者效率对比:

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <sys/time.h>
#include <list> using namespace std; template<class T>
void fun(const T& t, int sum)
{
for(int i = ; i < sum; i++)
t.find(i);
} template<template <class...> class T>
float init(int sum)
{
T<int,int> t;
for(int i = ; i < sum; i++)
t.insert(make_pair(i,i));
struct timeval begin,end;
gettimeofday(&begin,NULL);
fun(t,sum);
gettimeofday(&end,NULL);
float time = end.tv_sec-begin.tv_sec + float(end.tv_usec-begin.tv_usec)/;
cout<<"\033[32msum: "<<sum<<"\ttime: "<< time <<" sec"<<endl;
return time;
} int main(int argc,char** argv)
{
list<int> lt;
for(int i = ; i <= ; i*=)
{
lt.push_back(i);
}
for(auto& item : lt)
std::cout<<"\033[31m"<<init<unordered_map>(item)/init<map>(item) <<"\033[0m\n-------------------\n"<<std::endl;
}

本机测试结果为(Intel(R) Xeon(R) CPU           E5620  @ 2.40GHz):

map 与 unordered_map

例子:

#include <iostream>
#include <string>
#include <unordered_map>
#include <map> struct Test
{
int gameid;
int subgameid;
int roomid; //实现 map 的键条件:
bool operator<(const Test& obj) const
{
if(gameid < obj.gameid)
return true;
else if(gameid == obj.gameid && subgameid < obj.subgameid)
return true;
else if(gameid == obj.gameid && subgameid == obj.subgameid && roomid < obj.roomid)
return true;
else
return false;
} //实现 unordered_map 的键条件之一,还有一条件为实现hash算法
bool operator==(const Test& obj) const
{
return gameid == obj.gameid && subgameid == subgameid && roomid == obj.roomid;
} }; //第一种方法:
namespace std
{
template <typename T>
class hash
{
public:
long operator()(const T& o) const { return ; }
}; template <> class hash<Test>
{
public:
long operator()(const Test& x) const
{
return x.gameid* + x.subgameid* + x.gameid;
}
};
} //第二种方法
class test_hash
{
public:
long operator()(const Test& x) const
{
return x.gameid* + x.subgameid* + x.gameid;
}
}; int main()
{
std::unordered_map<Test,int> m1;
std::unordered_map<Test,int,test_hash> m2;
std::map<Test,int> m;
Test test1{,,};
Test test2{,,};
Test test3{,,};
m.insert(std::make_pair(test1,));
m.insert(std::make_pair(test2,));
Test test4{,,};
std::cout<<m.size()<<std::endl;
std::cout<<m[test4]<<std::endl;
}