std::unordered_map - how to “track” max/min key at any time

后端 未结 2 385
栀梦
栀梦 2021-01-16 13:36

I have std::unordered_map. I do not want to use other structures like tree or anything else cause latency requirements. But at any time I need t

2条回答
  •  醉梦人生
    2021-01-16 14:10

    You can write a wrapper. With that, you get every insertion/deletion and can retain min / max values.

    #pragma once
    
    #include 
    
    using std::unordered_map;
    
    class my_unordered_map
    {
    public:
        void insert(int key, int value)
        {
            _map[key] = value;
            if (_max < value)
                _max = value;
            if (_min> value)
                _min = value;
        }
        int get(int key)
        {
            auto it = _map.find(key);
            if (it != _map.end())
                return it->second;
            return 0; // or some error handling here.
        }
        int getMin()
        {
            return _min;
        }
        int getMax()
        {
            return _max;
        }
        // more functionality here.
    private:
        unordered_map _map;
        int _min = 0;
        int _max = 0;
    };
    

提交回复
热议问题