rewrite access to collection to avoid “double” finding

前端 未结 4 1072
广开言路
广开言路 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 04:58

    You can use this overload of insert instead:

    std::pair insert( const value_type& value );

    Example:

    std::unordered_map m { {0, "A"}, {1, "B"}, {2, "C"} };
    
    int orderId = 1;
    // attempt to insert with key you have and default constructed value type
    auto p = m.insert( std::make_pair(orderId, std::string()) );
    
    if (p.second) {
        // the element was inserted
    } else {
        // the element was not inserted
        std::cout << p.first->second;  // will print "B"
    }
    

    In both cases, p.first is the iterator to the element you search for (or just got inserted).

提交回复
热议问题