容器类之 unordered_map

该容器的特点
  1. 存放数据的方式:key = value,通过key进行检索。
  2. 存放数据时无序的。
  3. 检索的速度比map类快。
  4. 重载了[ ]运算符。
  5. iterator可以访问keyvalue

    unordered_map<int, bool> m = {
            { 5, true },
            { 6, true }
        };
    unordered_map<int, bool>::iterator it = m.begin();
    int key = it->first;
    bool b = it->second;
    
与检索相关的成员函数
  1. operator[key]

    查找成功:返回value引用(reference)

    查找失败:在map后面插入一个新的元素,key为当前查找的值,value在未赋值的情况下是为空的。

    // unordered_map::operator[]
    #include <iostream>
    #include <string>
    #include <unordered_map>
    using namespace std;
    
    int main ()
    {
      unordered_map<string,string> mymap;
    
      mymap["Bakery"]="Barbara";    // not found, new element inserted
      mymap["Seafood"]="Lisa";      // not found, new element inserted
      mymap["Produce"]="John";      // not found, new element inserted
    
      string name = mumap["XXXXX"]; // not found, the new element inserted, but the value is NULL.
    
      for (auto& x: mymap) {
        cout << x.first << ": " << x.second << endl;
      }
    
      return 0;
    }
    
    output result:
        Bakery: Barbara
        Seafood: Lisa
        Produce: John
        XXXXX: 
    

    auto& x : mymap:使用智能指针进行遍历。

  2. find(key)

    查找成功:返回一个iterator,指向该元素。

    查找失败:返回一个iterator,指向map.end()

  3. at(key)

    查找成功:返回引用。

    查找失败:抛出out_of_range#include <stdexcept>)异常。

    #include <iostream>       // std::cerr
    #include <stdexcept>      // std::out_of_range
    #include <vector>         // std::vector
    
    int main (void) {
        std::unordered_map<int, bool> m = {
            { 5, true },
            { 6, true }
        };
    
        int i = 7;
    
        try {
            m.at(i);    //find the value of which the key is 7.
        } catch (const std::out_of_range& oor) {
            std::cerr << "Out of Range error: " << oor.what() << '\n';
            std::cerr << "Out of Range error: " << "the key " << i << " not found." << '\n';
        }
    
        return 0;
    }
    

    orr.what():打印错误流中的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值