Home > Blockchain >  Updating map values in place
Updating map values in place

Time:06-08

How could I simplify this code to update the int value in the map in place?

Basically I want to leave the exceeds unchanged (which is the bool) and just update the int value.

std::map<OrderInfo, std::pair<int, bool>> ncpOrders;

int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
    auto it = ncpOrders.find(ordInfo);
    const bool firstTimeProcessing = it == ncpOrders.end();
    auto v = it->second;
    const int newAttempts = (firstTimeProcessing ? 0 : v.first)   1;
    const bool exceeds = firstTimeProcessing ? false : v.second;
    ncpOrders[ordInfo] = std::pair(newAttempts, exceeds);
    return newAttempts;
}

CodePudding user response:

You make this over-complicated. Note that default construction of std::pair<int, bool> meets your requirement, so you can just do:

std::map<OrderInfo, std::pair<int, bool>> ncpOrders;

int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
    return   ncpOrders[ordInfo].first;
}

and outcome should be exact the same.

https://godbolt.org/z/c1Ghsb4Ps

CodePudding user response:

You could use std::map::try_emplace to achieve this. Note that in this case since the default constructed value already matches your desired initial value, @MarekR's approach yields simpler code.

int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
    return   (ncpOrders.try_emplace(ordInfo, 0, false).first->second.first);
}

The result of std::map::try_emplace is a std::pair<iterator, bool> containing the position corresponding to the key after the operation. ->second.first provides you with the first member variable of the map value.

Note: You imho should change the parameter of your function to OrderInfo const& ordInfo: the parameter passed is never modified and must be comparable with its const version, so adding const to makes this applicable in more scenarios.

CodePudding user response:

int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
    auto it = ncpOrders.find(ordInfo);
    const bool firstTimeProcessing = it == ncpOrders.end();
    if (firstTimeProcessing) {
        ncpOrders[ordInfo] = std::pair(1, false);
        return 1;
    }
    else {
        auto v = it->second;
        return   v.first; // increment New Attempts
    }
}

there was a bug in the original code, I guess this is as concise as I can get it. I'm new to C so hopefully I didn't make some incorrect assumptions about being able to use prefix

  • Related