map、hash_map、unordered_map

相同点:
1.都是关联容器,关联容器将值与键关联在一起,并使用键来查找值,例如,值可以是表示雇员信息(如姓名、地址)的结构,而键可以是唯一的员工编号。为获取雇员信息,为获取雇员信息,程序将使用键查找雇员结构。2.键是唯一的。
不同点
map是有序关联容器,是经过排序的,这让它们能够使用表示“小于”概念的比较谓词。其底层是基于树结构实现的。hash_map、unordered_map都是无序关联容器,它们使用的是基于概念“等于”的比较谓词,其底层都是基于哈希表实现的。添加和删除元素的速度比较快以及查找算法的效率也很高,
在c++语言中,第一个广泛使用的哈希表实现是 (SGI)标准模板库(STL)中的hash_map、hash_set、hash_multiap、hash_multiset类模板。由于其实用性,它们后来被包含在c++标准库的其他几个实现中(例如,GNU编译器集合的libstdc++和Visual c++标准库)。hash_*类模板被提交到c++技术报告1 (c++ TR1)中,并以unordered_*的名称接受。后来,它们被合并到c++标准的c++ 11修订版中。
总体来说,hash_map或者unordered_map 查找速度会比map快,属于常数级别;而map的查找速度是log(n)级别。并不一定常数就比log(n)小,hash还有hash函数的耗时。如果你考虑效率,特别是在元素达到一定数量级时,可以考虑hash_map或者unordered_map。但若你对内存使用特别严格,希望程序尽可能少消耗内存,那么hash_map或者unordered_map可能就没map效果好了。

具体如何使用以及三者之间的比较实现代码如下:

#include<cstdio>
#include<cstdlib>
#include<map>
#include<hash_map>
#include<unordered_map>
using std::string;

void test_map(){
	std::map<string, string> map;
	map["xiao ming"] = "21";
	map["xiao hua"] = "20";
	map["xiao bai"] = "23";
	map["lao zhang"] = "52";
	std::map<string, string>::iterator it;
	it = map.find("xiao bai");
	if (it != map.end())
		printf("%s.\n", (*it).second.c_str());

	for (it = map.begin(); it != map.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
	map.erase("lao zhang");
	printf("after erase:\n");
	for (it = map.begin(); it != map.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
}
void test_hash_map(){
	std::hash_map<string, string> hashmap;
	hashmap["xiao ming"] = "21";
	hashmap["xiao hua"] = "20";
	hashmap["xiao bai"] = "23";
	hashmap["lao zhang"] = "52";
	std::hash_map<string, string>::iterator it;
	it = hashmap.find("xiao bai");
	if (it !=  hashmap.end())
		printf("%s.\n", (*it).second.c_str());

	for (it = hashmap.begin(); it != hashmap.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
	hashmap.erase("lao zhang");
	printf("after erase:\n");
	for (it = hashmap.begin(); it != hashmap.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
}

void test_unordered_map(){
	std::unordered_map<string, string> unorderedmap;
	unorderedmap["xiao ming"] = "21";
	unorderedmap["xiao hua"] = "20";
	unorderedmap["xiao bai"] = "23";
	unorderedmap["lao zhang"] = "52";
	std::unordered_map<string, string>::iterator it;
	it = unorderedmap.find("xiao bai");
	if (it != unorderedmap.end())
		printf("%s.\n", (*it).second.c_str());

	for (it = unorderedmap.begin(); it != unorderedmap.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
	unorderedmap.erase("lao zhang");
	printf("after erase:\n");
	for (it = unorderedmap.begin(); it != unorderedmap.end(); ++it){
		printf("%-10s : %s \n", (*it).first.c_str(), (*it).second.c_str());
	}
}
int main(){
	test_map();
	printf("\n\n");
	test_hash_map();
	printf("\n\n");
	test_unordered_map();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/K123966/article/details/88778389