Least Recently Used cache using C++

前端 未结 7 1311
甜味超标
甜味超标 2020-12-14 05:04

I am trying to implement LRU Cache using C++ . I would like to know what is the best design for implementing them. I know LRU should provide find(), add an element and remov

7条回答
  •  情书的邮戳
    2020-12-14 05:29

    The best way to implement an LRU is to use the combination of a std::list and stdext::hash_map (want to use only std then std::map).

    • Store the data in the list so that the least recently used in at the last and use the map to point to the list items.
    • For "get" use the map to get the list addr and retrieve the data and move the current node to the
      first(since this was used now) and update the map.
    • For "insert" remove the last element from the list and add the new data to the front and update the map.

    This is the fastest you can get, If you are using a hash_map you should almost have all the operations done in O(1). If using std::map it should take O(logn) in all cases.

    A very good implementation is available here

提交回复
热议问题