map查找

1,auto value = map.at(“test”); 如果map中没有这个key会报错。
2,auto value = map[“test”]; 没有不会报错,且会插入一个新的pair,value为空。
源码如下:

T& operator[](const key_type& k)
{
	return (*((insert(value_type(k, T()))).first)).second;
}

3,用map自己提供的find函数即可,完全没有副作用。如下map_find:

    #include <iostream>
    #include <string>
    #include <map>
    #include <algorithm>
    using namespace std;
    
    string map_find(const map<string,string> &map,const string &key)
    {
        auto it = map.find(key);
        if(it != map.end())
            return it->second;
        return "";
        //    return map.find(key)!=map.end() ? map.find(key)->second : "";
    }
    
    int main()
    {
        map<string,string> map{std::make_pair("111","test"),std::make_pair("222","test2"),std::make_pair("333","test3"),};
        cout <<"Before:"<<endl;
        for_each(map.begin(),map.end(),[](auto &pa){cout<<"first:"<<pa.first<<",second:"<<pa.second<<endl;});
        cout <<"After:"<<endl;
        //auto value = map.at("test");//err
        auto value = map["test"];//自动添加一个pair元素
        auto value2 = map_find(map,"test");
        if(value2.empty())
            cout<<"empty..."<<endl;//这里的empty有两个含义:要么是没有这个key存在;要么存在,但是value是空。
        else
            cout<<value2<<endl;
        for_each(map.begin(),map.end(),[](auto &pa){cout<<"first:"<<pa.first<<",second:"<<pa.second<<endl;});
    
        return 0;
    }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值