Rookie Engineer

If you aren't the kind of person that feels this way naturally, you'll need to become one in order to make it as a hacker. Otherwise you'll find your hacking energy is sapped by distractions like sex, money, and social approval.

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  24 Posts :: 0 Stories :: 2 Comments :: 0 Trackbacks

常用链接

留言簿

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜


[转]http://biancheng.dnbcw.info/c/170128.html

标准std中只有map,是使用平衡二叉树实现的,查找和添加的复杂度都为O(log(n)),
没有提供hash map,gnu c++提供了hash_map,是一个hash map的实现,查找和添加复杂
度均为O(1)。
#include <ext/hash_map>
#include <iostream>
#include <cstring>

using namespace std; 
using namespace __gnu_cxx;

struct eqstr{
	bool operator()(const char *s1, const char *s2)const{
		return strcmp(s1,s2) == 0;
	}
};

int main(){
	hash_map<const char *,int,hash<const char *>,eqstr> months;
	months["january"] = 31;
	months["february"] = 28;
	months["march"] = 31;
	cout << "march -> " << months["march"] << endl;
}

不过gnu hash_map和c++ stl的api不兼容,c++ tr1(C++ Technical Report
1)作为标准的扩展,实现了hash map,提供了和stl兼容一致的api,称为unorder_map.在头文件
<tr1/unordered_map>中。另外c++ tr1还提供了正则表达式、智能指针、hash table、
随机数生成器的功能。
#include <iostream>
#include <string>
#include <tr1/unordered_map>
using namespace std;

int main(){
	typedef std::tr1::unordered_map<int,string> hash_map;
	hash_map hm;
	hm.insert(std::pair<int,std::string>(0,"Hello"));
	hm[1] = "World";
	for(hash_map::const_iterator it = hm.begin(); it != hm.end(); ++it){
		cout << it->first << "-> " << it->second << endl;
	}
	return 0;
}
posted on 2011-11-11 10:29 micwu 阅读(20206) 评论(0)  编辑 收藏 引用 所属分类: C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理