Effective STL学习笔记-条款24

当关乎效率时应该在map::operator[]和map-insert之间仔细选择

假设有一个支持默认构造函数和赋值构造函数的类:

class Widget
{
public:
    Widget() {}
    Widget(int) {}
    const Widget& operator=(int) {}
};

    map<int, Widget> map;
    map[0] = 0;
    map[1] = 1;
    map[2] = 2;

书上说,这种情况下使用operator[]操作的map,会先创建一个Widget临时变量,随后析构这个临时变量,最后进行一个赋值操作。
实际上根据我的测试,个人认为临时变量以已经被移动构造优化了。

在map操作最重要的应该是,key是否存在,然后进行所需要的操作,这里给出一个简单的判断key存在的示例:

//每个map必须的key值都需要在这里声明
enum class MapParam
{
    Apple,
    Lemon,
    Peach
};

using paramMap = map<MapParam, string>;

//判断是否存在某个key 这个key取值于MapParam
template<typename Key>
bool isExistParam(paramMap thisMap, Key key)
{
    return thisMap.find(key) != thisMap.end();
}

//获取某个key下的value
template<typename ReturnType, typename Key>
ReturnType getParam(paramMap thisMap, Key key)
{
    auto constIter = thisMap.find(key);

    if (constIter == thisMap.end())
    {
        //throw
    }
    return constIter->second;
}


    paramMap thisMap;
    thisMap.insert(make_pair<MapParam, string>(MapParam::Apple, "Apple"));
    thisMap.insert(make_pair<MapParam, string>(MapParam::Lemon, "Lemon"));
    if (isExistParam(thisMap, MapParam::Apple))
    {
        cout << getParam<std::string>(thisMap, MapParam::Apple) << endl;
    }
    if (isExistParam(thisMap, MapParam::Lemon))
    {
        cout << getParam<std::string>(thisMap, MapParam::Lemon) << endl;
    }
    if (isExistParam(thisMap, MapParam::Peach))
    {
        cout << getParam<std::string>(thisMap, MapParam::Peach) << endl;
    }

这个map没有peach这个key所以打印:

Apple
Lemon
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值