两者效率对比:
#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 = 0; i < sum; i++)t.find(i); }template<template <class...> class T> float init(int sum) {T<int,int> t;for(int i = 0; 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)/1000000;cout<<"\033[32msum: "<<sum<<"\ttime: "<< time <<" sec"<<endl;return time; }int main(int argc,char** argv) {list<int> lt;for(int i = 1; i <= 10000000; i*=10){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):
例子:
#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;elsereturn 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 0; }};template <> class hash<Test>{public:long operator()(const Test& x) const{return x.gameid*100 + x.subgameid*10 + x.gameid;}}; }//第二种方法 class test_hash {public:long operator()(const Test& x) const{return x.gameid*100 + x.subgameid*10 + 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{3,3,3};Test test2{1,2,4};Test test3{1,2,4};m.insert(std::make_pair(test1,10));m.insert(std::make_pair(test2,20));Test test4{3,3,3};std::cout<<m.size()<<std::endl;std::cout<<m[test4]<<std::endl; }