重写对集合的访问以避免“双重"访问.发现 [英] rewrite access to collection to avoid "double" finding
本文介绍了重写对集合的访问以避免“双重"访问.发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的代码:
std::unordered_map<int64_t /*id_ord*/, LimitOrder> futOrders;
auto i = futOrders.find(orderId);
if (i == futOrders.end()) {
LimitOrder& newOrder = futOrders[orderId];
// work
} else {
LimitOrder& futOrder = i->second;
// another work
}
我在这里执行两次查找":第一次: auto i = futOrders.find(orderId);
第二次: LimitOrder&newOrder = futOrders [orderId];
Here I execute "find" twice:
first time: auto i = futOrders.find(orderId);
second time: LimitOrder& newOrder = futOrders[orderId];
我可以以某种方式重写它以避免重复查找"吗?
Can i rewrite it somehow to avoid "double find"?
推荐答案
您可以执行 emplace
,并检查返回值以了解是否插入了该项目:
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
}
这篇关于重写对集合的访问以避免“双重"访问.发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文