c++中unordered_map的用法

本文深入探讨了C++11标准容器unordered_map的基本用法,包括构造函数、数据添加、元素查找与删除等关键操作,以及内部哈希表的存储与搜索机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unordered_map是c++-11新加的一个标准容器,它提供了一对一的关系,并且在查找速度上能达到O
(1)的速度。本文总结了它的一些基本用法,以供以后参考。

1.unordered_map的构造函数

unordered_map<string,int> mapstring;

unordered_map<int,string> mapint;

unordered_map<string,char> mapchar;

        其中第一个参数为主值的类型,第二个参数为键值的类型。unordered_map内部使用哈希表进行存储与搜索。

2.map添加数据

unordere_map<int,string> maplive;
//method 1
maplive.insert(pair<int,string>(102,"active"));
//method 2
maplive.insert(unordered_map<int,string>::value_type(321,"hello"));
//method 3
maplive[112]="April";  //这种方法是最简单用的最多的

 

3.   unordered_map中元素的查找

    find()函数返回一个迭代器指向键值为key的元素,如果没有找到就返回指向map尾部的迭代器。

unordered_map<int,string>::iterator it;
//如果想要偷懒也可以这样写    auto it;
it = maplive.find(112);  
if(it!=maplive.end())
     cout<<"we find key 112.";
else
     cout<<"we don't find 112.";

4. unordered_map中元素的删除

    erase(it)函数会删除迭代器it指向的元素。

//删除键值为112的元素
auto it;
it=maplive.find(112);
if(it==maplive.end())
    cout<<"we don't find 112."<<endl;
else
    maplive.erase(it); //delete 112

5.unordered_map中元素的查找  count

          count(a)会返回a元素在map中出现的次数,如果没有出现就返回0.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值