LRUCache-c++实现

代码

//LRUCache.h
#ifndef LRUCACHE_H_
#define LRUCACHE_H_

#include <utility>
#include <unordered_map>
#include <list>

template<class KeyType, class ValueType>
class LRUCache {
public:
    LRUCache(int capacity) : cap_(capacity) {}
    bool get(KeyType key, ValueType& value);
    void put(KeyType key, ValueType value);
private:
    typedef std::pair<int, int> Node;
    typedef typename std::list<Node>::iterator Iter; // 注意typename的用法

    std::list<Node> cache_list_;
    std::unordered_map<KeyType, Iter> cache_map_;
    int cap_;
};

template<class KeyType, class ValueType>
bool LRUCache<KeyType, ValueType>::get(KeyType key, ValueType& value){
    if( cache_map_.find(key) == cache_map_.end() ) return false;
    else{
        Iter it = cache_map_[key];

        // get the value
        value = cache_map_[key]->second;

        // move to head
        cache_list_.splice(cache_list_.begin(), cache_list_, it);

        return true;
    }
}

template<class KeyType, class ValueType>
void LRUCache<KeyType, ValueType>::put(KeyType key, ValueType value){
    if( cache_map_.find(key) != cache_map_.end() ){
        Iter it = cache_map_[key];

        // update the value
        it->second = value;

        // move to head
        cache_list_.splice(cache_list_.begin(), cache_list_, it);
    }
    else{
        Node node(key, value);

        if( cache_list_.size() == cap_ ){
            cache_map_.erase(cache_list_.back().first);
            cache_list_.pop_back();
        }

        cache_list_.push_front(node);
        cache_map_[key] = cache_list_.begin();
    }
}

#endif

说明

自己实现过程中几个坑:
1. 模板的头文件和源文件不能分离编译。也就是说要写成一个整体。
2. 注意上面typename的用法,这个点卡了我一段时间。原因是对于模板的成员,编译器不知道这到底是个类型还是个变量(类的静态变量).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值