Remove element from std::map based on the time of insertion

后端 未结 3 1451
栀梦
栀梦 2021-02-20 00:30

I need to erase elements from an std::map based on the time of insertion (or something else more efficient than that).

The map will probably hold thousands of elements a

3条回答
  •  时光说笑
    2021-02-20 00:45

    Pretty close to LRU Cache.

    The Boost.MultiIndex library shows an example of MRU Cache (Most Recently Used), so adapting it to LRU should be trivial.

    Basically the idea is to maintain two data structures in parallel:

    • a map with the items in
    • a deque with references into the map

    Basic code:

    static double const EXPIRY = 3600; // seconds
    
    std::map map;
    std::deque::iterator, time_t>> deque;
    
    bool insert(Key const& k, Value const& v) {
      std::pair::iterator, bool> result =
        map.insert(std::make_pair(k, v));
    
      if (result.second) {
        deque.push_back(std::make_pair(result.first, time()));
      }
    
      return result.second;
    }
    
    // to be launched periodically
    void clean() {
      while (not deque.empty() and difftime(time(), deque.front().second) > EXPIRY) {
        map.erase(deque.front().first);
        deque.pop_front();
      }
    }
    

    Of course, those structures need be synchronized if the intent is to get multi-threaded code.

提交回复
热议问题