Is it ok to use mutable to decrease all the keys in std::map by the same value?

131 Views Asked by At

As far as I know, std::map is almost always implemented as some kind of self-balancing search tree. Therefore, I assume decreasing every key by the same value should not result in undefined behaviors or corrupt the map? Is the following code actually safe?

#include <map>
#include <iostream>
using namespace std;

struct Key {
    mutable int val;
    bool operator<(Key const& other) const {
        return val < other.val;
    }
};
int main() {
    map<Key,int> mp {
        {{1},2},{{3},4},{{5},6},{{7},9}
    };
    for (auto&& kvp : mp) {
        kvp.first.val -= 2;
    }
    mp.emplace(Key{2},3);
    for (auto&& kvp : mp) {
        cout << kvp.first.val << ":" << kvp.second << " ";
    }
    cout << endl;

// should print -1:2 1:4 2:3 3:6 5:9 
}

As for use cases, I think this might be useful to implement an event queue where each event is associated with a timer and will be fired if the timer reaches 0.

0

There are 0 best solutions below