开发者

C++ Best container for really simple LRU cache

I need to implement a really simple LRU cache which stores memory addresses.

  • The count of these addresses is fixed (at runtime).
  • I'm only interested in the last-recently used address (I don't care about the order of the other elements).
  • Each address has a corresponding index number (simple integer) which isn't unique and can change.

The implementation needs to run with as less overhead as possible. In addition to each address, there's is also a related info structure (which contains the index).

My current approach is using a std::list to store the address/info pair and a boost::unordered_multimap which is a mapping between the index and the related iterator of the list.

The following example has nothing to do with my production code. Please note, that this is just for a better understanding.

struct address_info
{
    address_info() : i(-1) {}
    int i;
    // more ...
};


int main()
{
    int const MAX_ADDR_COUNT = 10,
              MAX_ADDR_SIZE  = 64;

    char** s           = new char*[MAX_ADDR_COUNT];
    address_info* info = new address_info[MAX_ADDR_COUNT]();

    for (int i = 0; i < MAX_ADDR_COUNT; ++i)
        s[i] = new char[MAX_ADDR_SIZE]();

    typedef boost::unordered_multimap<int, std::list<std::pair<address_info, char*>>::const_iterator> index_address_map;

    std::list<std::pair<address_info, char*>> list(MAX_ADDR_COUNT);
    index_address_map                  map;

    {
        int i = 0;
        for (std::list<std::pair<address_info, char*>>::iterator iter = list.begin(); i != MAX_ADDR_COUNT; ++i, ++iter)
            *iter = std::make_pair(info[i], s[i]);
    }

    // usage example:
    // try to find address_info 4
    index_address_map::const_iterator iter = map.find(4);
    if (iter == map.end())
    {
        std::pair<address_info, char*>& lru = list.back();

        if (lr开发者_开发百科u.first.i != -1)
            map.erase(lru.first.i);
        lru.first.i = 4;

        list.splice(list.begin(), list, boost::prior(list.end()));
        map.insert(std::make_pair(4, list.begin()));
    }
    else
        list.splice(list.begin(), list, iter->second);

    for (int i = 0; i < MAX_ADDR_COUNT; ++i)
        delete[] s[i];

    delete[] info;
    delete[] s;

    return 0;
}


The usual recommendation is to dig up Boost.MultiIndex for the task:

  • index 0: order of insertion
  • index 1: key of the element (either binary search or hash)

It's even demonstrated on Boost site if I recall correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜