
hash表表项是 (键-值) 对(key-value)
hash表的健和值可以是任何类型,可以是int、结构体、对象、对象的指针…
#include //map为#include
unordered_map<Node*, Node*> tablenode; //Node*类型
unordered_map<int, string> table={{5,"a"},{6,"b"}}; //直接初始化
二. 插入(3种)
table[3] = "c"; //通过键修改值,有则改,若无则不改
table.insert(pair<int, string>(3, "c")); //使用insert和pair插入
table.insert(Map::value_type(3, "c"));
三. 删除
按键删除
table.erase(5); //删除键为5的对,返回一个迭代器
四. 遍历(4种)
unordered_map 等于 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)
五. 查找(2种)
均是按键找值
table.find(2) //find返回一个迭代器,不存在就返回table.end()
table.count(2) //count判断key是否存在,存在返回1,否则返回0
对比:
unordered_map无序,比map快,但map内存占用略低
底层实现:
map: 红黑树,具有自动排序的功能
unordered_map: 哈希表,无序
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)