rewrite access to collection to avoid “double” finding

前端 未结 4 1031
广开言路
广开言路 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<iterator,bool> insert( const value_type& value );

    Example:

    std::unordered_map<int, std::string> 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).

    0 讨论(0)
  • 2021-01-25 05:00

    Assuming there is a way to "determine if an order is empty", you could do:

    LimitOrder& anOrder = futOrders[orderId];
    
    if (anOrder.empty())       
    {
       // New order, do stuff that only new orders need. 
    }
    else
    {
       // Old order, update it.
    }
    

    The empty method could of course be something like if (anOrder.name == "") or if (anOrder.orderId == 0), etc.

    0 讨论(0)
  • 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<int64_t /*id_ord*/, LimitOrder> 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
    }
    
    0 讨论(0)
  • 2021-01-25 05:19

    How about using size() to realize if an element was inserted, like this:

    auto old_size = futOrders.size();
    LimitOrder& order = futOrders[orderId];
    if (old_size < futOrders.size()) {
        LimitOrder& newOrder = order;
            // work
    } else {
        LimitOrder& futOrder = order;
            // another work
    }
    
    0 讨论(0)
提交回复
热议问题