unordered_map(2)

本文详细介绍了C++ STL库中的unordered_map容器,重点讲解了[]运算符的重载功能,包括元素的访问和插入操作,以及operator=的三种重载形式。通过示例代码展示了如何使用这些功能进行元素的操作。

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

unordered_map 重载了[ ] 运算符。

mapped_type& operator[] ( const key_type& k );
mapped_type& operator[] ( key_type&& k );

访问元素:

如果k匹配到了容器中的元素,则该该函数返回其引用值的引用。

如果k与容器中任何元素都不匹配,则该函数使用该键插入一个新元素,并返回其引用值的引用。请注意,即使没有为元素指定映射值(使用其默认构造函数构造元素),这也会将容器大小增加1。

类似的成员函数unordered_map :: at在具有键的元素存在时具有相同的行为,但在不存在时抛出异常。

返回值:

对具有等于k键值元素映射值的引用。

如果插入了新元素,则使用allocator_traits <allocator_type> :: construct()分配其存储,这可能会在失败时抛出异常(对于默认分配器,如果分配请求不成功则抛出bad_alloc)。

例子:

#include<unordered_map>
#include<string>
#include<iostream>
int main()
{
    std::unordered_map<std::string,std::string> mymap;

    mymap["Bakery"]="Barbara";  // new element inserted
    mymap["Seafood"]="Lisa";  // new element inserted
    mymap["Produce"]="John";
    for(auto i=0;i<mymap.bucket_cout;i++){
        std::cout<<"bucket #"<<i<<":";
        for(auto local_it=mymap.begin(i);local_it!=mymap_end(i);local_it++)
            std::cout<<local_it->first()<<" :"<<local_it->second();
        std::cout<<std::endl;
        }
    std::string name=myamp["Bakery"]; // existing element accessed (read)
    mymap["Produce"]=name;// existing element accessed (written)

     mymap["Bakery"] = mymap["Produce"];   // existing elements accessed (read/written)

    name=mymap["Deli"]; // non-existing element: new element "Deli" inserted!
    
    return 0;
}

注意:unordered_set没有重载 [ ] 运算符,unordered_map提供 [ ]并不是用于顺序访问,而是根据const key_type& k 找到对应的value值。

unordered_map::operator=

copy (1)
unordered_map& operator= ( const unordered_map& ump );
move (2)
unordered_map& operator= ( unordered_map&& ump );
initializer list (3)
unordered_map& operator= ( intitializer_list<value_type> il );

unordered_map 重载=运算符,用于指定容器新的内容。

第一个执行复制赋值,它将ump的所有元素复制到容器对象中(ump保留其内容)。

第二个执行移动分配,其将ump的内容的所有权转移到对象。没有副本出现:内容被ump丢失。

第三个将初始化列表il的内容指定为容器对象的元素。

例子:

#include<iostream>
#include<string>
#include<unordered_map>
typedef std::unordered_map<std::string,std::string> stringmap;
stringmap merge (stringmap a,stringmap b) {
  stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
int main()
{
    stringmap first,second,third;
    first={{"AAPL","APPLE"},{"MSFT","Microsoft"}};//list init
    second={{"good", "google"},{"orcl","oral"}};
    third=merge(first,second);//move
    first=third;//copy
    std::cout << "first contains:";
    for(auto& x:first)
    std::cout<<" " <<x.first()<< " "<<x.second();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值