rewrite access to collection to avoid “double” finding

前端 未结 4 1071
广开言路
广开言路 2021-01-25 04:43

I have such code:

std::unordered_map futOrders;

auto i = futOrders.find(orderId);
if (i == futOrders.end()) {
    LimitOrd         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 05:19

    You can perform an emplace, and check the return value to know whether the item was inserted or not:

    std::unordered_map futOrders;
    
    auto i = futOrders.emplace(
               std::piecewise_construct, std::tie(orderId), std::make_tuple());
    if (i.second) {
        LimitOrder& newOrder = i.first->second;
                // work
    } else {
        LimitOrder& futOrder = i.first->second;
                // another work
    }
    

提交回复
热议问题