C++ 哈希表

从2011年开始,C++支持非排序的unordered_map和unordered_set(原先的map和set都是通过有序结构实现的)

下面是一些性能上的测试

#include<iostream>
#include<ctime>
#include<map>
#include<set>
#include<cstdlib>
#include<unordered_map>
#include<unordered_set>
#include<string>
using namespace std;
int main(){
	int n=100000;
	vector<string> vec;
	srand(unsigned(time(0)));
	for(int i=0;i<n;i++){
		string s;
		for(int j=0;j<30;j++){
			s+='a'+rand()%26;
		}
		vec.push_back(s);
	}
	clock_t start,end;
	set<string> tm;
	unordered_set<string>hm;
	start=clock();
	for(int i=0;i<n;i++){
		hm.insert(vec[i]);
	}
	end=clock();
	cout<<"unordered_set:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<n;i++){
		tm.insert(vec[i]);
	}
	end=clock();
	cout<<"set:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<100000;i++){
		if(hm.find(vec[i])!=hm.end()){}
	}
	end=clock();
	cout<<"unordered_set:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<100000;i++){
		if(tm.find(vec[i])!=tm.end()){}
	}
	end=clock();
	cout<<"set:"<<end-start<<endl;
	return 0;
}

unordered_set:7417
set:1228
unordered_set:511
set:1050

#include<iostream>
#include<ctime>
#include<map>
#include<set>
#include<cstdlib>
#include<unordered_map>
#include<unordered_set>
#include<string>
using namespace std;
int main(){
	int n=100000;
	vector<string> vec;
	srand(unsigned(time(0)));
	for(int i=0;i<n;i++){
		string s;
		for(int j=0;j<30;j++){
			s+='a'+rand()%26;
		}
		vec.push_back(s);
	}
	clock_t start,end;
	map<string,bool> tm;
	unordered_map<string,bool>hm;
	start=clock();
	for(int i=0;i<n;i++){
		hm[vec[i]]=true;
	}
	end=clock();
	cout<<"unordered_map:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<n;i++){
		tm[vec[i]]=true;
	}
	end=clock();
	cout<<"map:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<100000;i++){
		if(hm[vec[i]]){}
	}
	end=clock();
	cout<<"unordered_map:"<<end-start<<endl;
	start=clock();
	for(int i=0;i<100000;i++){
		if(tm[vec[i]]){}
	}
	end=clock();
	cout<<"map:"<<end-start<<endl;
	return 0;
}

unordered_map:7894
map:1722
unordered_map:497
map:959

对自定类型使用hash表

class Pair{
  public:
  int a;
  int b;
  Pair(){}
  Pair(int a1,int b1){
    a=a1;
    b=b1;
  }
  bool operator==(const Pair& p)const{
	return a==p.a&&b==p.b;
  }
};
struct Hash_Pair
{
  size_t operator()(const Pair &p) const
  {
    double temp=p.a;
    temp+=p.b*2147483647.0;
    hash<double> ht;//直接用了已经提供的hah函数,没有自己编写hash
    return ht(temp);
  }
};
struct Equal_Pair
{
  bool operator()(const Pair &left, const Pair &right) const
  {
    return left.a==right.a&&left.b==right.b;
  }
};
unordered_set<Pair,Hash_Pair,Equal_Pair>  set;
原文地址:https://www.cnblogs.com/superzrx/p/3329815.html