C++ 重写对集合的访问以避免;“双”字;发现

C++ 重写对集合的访问以避免;“双”字;发现,c++,C++,我有这样的代码: 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 =

我有这样的代码:

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
}
std::无序的订单;
自动i=futOrders.find(orderId);
如果(i==futOrders.end()){
LimitOrder&newOrder=futOrders[orderId];
//工作
}否则{
LimitOrder&futOrder=i->second;
//另一件作品
}
在这里,我执行两次“查找”: 第一次:
auto i=futOrders.find(orderId)
第二次:
LimitOrder&newOrder=futOrders[orderId]

我是否可以重写它以避免“双重查找”

使用
size()
来实现是否插入了元素,如下所示:

auto old_size = futOrders.size();
LimitOrder& order = futOrders[orderId];
if (old_size < futOrders.size()) {
    LimitOrder& newOrder = order;
        // work
} else {
    LimitOrder& futOrder = order;
        // another work
}
auto old_size=futOrders.size();
LimitOrder&order=futOrders[orderId];
如果(旧尺寸
假设有一种方法可以“确定订单是否为空”,您可以执行以下操作:

LimitOrder& anOrder = futOrders[orderId];

if (anOrder.empty())       
{
   // New order, do stuff that only new orders need. 
}
else
{
   // Old order, update it.
}

empty
方法当然可以类似于
if(anOrder.name==“”)
if(anOrder.orderId==0)
等。

您可以使用以下重载:

std::成对插入(常量值\u类型和值)

例如:

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"
}
无序映射m{0,“A”},{1,“B”},{2,“C”}; int orderId=1; //尝试使用您拥有的键和默认构造值类型插入 auto p=m.insert(std::make_pair(orderId,std::string()); 如果(第二页){ //该元素已插入 }否则{ //未插入元素 std::cout second;//将打印“B” }

在这两种情况下,
p.first
是您搜索(或刚刚插入)的元素的迭代器。

您可以执行
放置
,并检查返回值以了解项目是否插入:

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
}
std::无序的订单;
自动i=futOrders.emplace(
std::分段_构造,std::tie(orderId),std::make_tuple();
如果(一秒){
LimitOrder&newOrder=i.first->second;
//工作
}否则{
LimitOrder&futOrder=i.first->second;
//另一件作品
}

这样做的缺点是,即使映射中已经存在映射类型,也需要构造映射类型。(一种不必要且可能昂贵的操作)正确。我不知道
emplace
也能做到这一点+我对你的答案有信心。