hash表的简单使用 (unordered_map)

hash表表项是 (键-值) 对(key-value)
hash表的健和值可以是任何类型,可以是int、结构体、对象、对象的指针…

一.初始化
#include <unordered_map>  //map为#include <map>
unordered_map<Node*, Node*> tablenode;    //Node*类型
unordered_map<int, string> table={{5,"a"},{6,"b"}}; //直接初始化

//创建对应表项
table[2]="d";    //直接添加/修改

//如果值为int型,则默认为1
unordered_map<char,int> t;
string s;
for(auto i:s)  	//i不是迭代器
	t[i]++;     //计数
t['a']++;  		//等同于 t['a']=1;
二. 插入
table.insert(pair<int, string>(3, "c")); //使用insert和pair插入
table.insert(Map::value_type(3, "c"));  
三. 删除

删除

table.erase(5);  //删除键为5的对,返回一个迭代器
四. 遍历

unordered_map<int,string>::iterator i; 等于 auto i...
i为迭代器类型,i->first 为键,i->second 为值
i++; 为下一个元素

for(auto i:table){ 		//也可以传引用 auto& i:table;下同
	cout<<i->first<<i->second<<endl;}

for(auto [k,v]:table){   //auto [k,_]:map或者auto [_,v]:map可以单独遍历键或值
	cout<<k<<v<<endl;}
	
for(auto i = table.begin();i!table.end();i++) //常用
for(pair<int, string> i:table)
五. 查找

均是按找值

table.find(2) 	  //find返回一个迭代器,不存在就返回table.end()
table.count(2)    //count判断key是否存在,存在返回1,否则返回0

对比
unordered_map无序,比map快,但map内存占用略低

底层实现
map: 红黑树,具有自动排序的功能
unordered_map: 哈希表,无序

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值