posts - 501,comments - 0,views - 23802

unordered_map参考博客

区别在于unordered_multimap允许键值冗余,即key值可以是一样的,但是unordered_map不允许。

定义

主要使用的也是模板的前2个参数<键,值>
unordered_map<const Key, T> map;

insert()/map[key] = T

erase()

iterator erase ( const_iterator position );

  • 通过位置

size_type erase ( const key_type& k );

  • 通过key

iterator erase ( const_iterator first, const_iterator last );

  • 通过范围(两个迭代器)

迭代器it
unordered_map的迭代器是一个指针,指向这个元素,通过迭代器来取得它的值。

unordered_map<Key,T>::iterator it;
(*it).first;             // the key value (of type Key)
(*it).second;            // the mapped value (of type T)
(*it);                   // the "element value" (of type pair<const Key,T>) 

find()

查找key所在的元素。

  • 找到:返回元素的迭代器。通过迭代器的second属性获取值
  • 没找到:返回unordered_map::end

end()

end(): 返回结束位置的迭代器
end(int n) : 返回n号bucket的最后一个迭代器

at
mapped_type& at ( const key_type& k );
查找key所对应的值

  • 如果存在:返回key对应的值,可以直接修改,和[]操作一样。
  • 如果不存在:抛出 out_of_range 异常.

mymap.at(“Mars”) = 3396; //mymap[“Mars”] = 3396

count()
size_type bucket_count() const noexcept;

  • 返回通过哈希计算key所在的bucket(注意:这里仅仅做哈希计算确定bucket,并不保证key一定存在bucket中!
  • 返回bucket的总数
posted on   垂序葎草  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示