map/unordered_map原理和使用整理

本文对比分析了C++中的unordered_map和map,unordered_map基于哈希表提供高效查找,但内存占用较高,适合无序场景;而map采用红黑树实现,保证有序性但查找效率较低。根据具体需求选择合适的容器。
摘要由CSDN通过智能技术生成

1.结论

新版的hash_map都是unordered_map了,这里只说unordered_map和map.

运行效率方面:unordered_map最高,而map效率较低但 提供了稳定效率和有序的序列。

占用内存方面:map内存占用略低,unordered_map内存占用略高,而且是线性成比例的。

需要无序容器,快速查找删除,不担心略高的内存时用unordered_map;有序容器稳定查找删除效率,内存很在意时候用map

2.原理

map的内部实现是二叉平衡树(红黑树);hash_map内部是一个hash_table一般是由一个大vector,vector元素节点可挂接链表来解决冲突,来实现.

hash_map 其插入过程是:
  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 存放key和value在桶内。

其取值过程是:
  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 比较桶的内部元素是否与key相等,若都不相等,则没有找到。
  5. 取出相等的记录的value。

hash_map中直接地址用hash函数生成,解决冲突,用比较函数解决。

3.内存占用测试

测试代码:
测试条件window下,VS2015 C++。string为key, int 为value。
1.UnorderMap:
#include <unordered_map>  
#include <string>  
#include <iostream>
#include <windows.h>
#include <psapi.h>  
#pragma comment(lib,"psapi.lib") 
using namespace std;
using namespace stdext;
void showMemoryInfo(void)
{
	HANDLE handle = GetCurrentProcess();
	PROCESS_MEMORY_COUNTERS pmc;
	GetProcessMemoryInfo(handle, &pmc, sizeof(pmc));
	cout << "Memory Use:" << pmc.WorkingSetSize/1024.0f << "KB/" << pmc.PeakWorkingSetSize/1024.0f << "KB, Virtual Memory Use:" << pmc.PagefileUsage/1024.0f << "KB/" << pmc.PeakPagefileUsage/1024.0f << "KB" << endl;
}

//define the class  
/*-------------------------------------------*/
/*函数类
*作为hash_map的hash函数
*string没有默认的hash函数
*/
class str_hash {
public:
	size_t operator()(const string& str) const
	{
		unsigned long __h = 0;
		for (size_t i = 0; i < str.size(); i++)
			__h = 5 * __h + str[i];
		return size_t(__h);
	}
};

/*-------------------------------------------*/
/*函数类
*作为hash_map的比较函数 )
*(查找的时候不同的key往往可能对用到相同的hash值
*/
class str_compare
{
public:
	bool operator()(const string& str1, const string& str2)const
	{
		return   str1 == str2;
	}
};

struct CharLess : public binary_function<const string&, const string&, bool>
{
public:
	result_type operator()(const first_argument_type& _Left, 
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值