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: 哈希表,无序