LRUのsetとgetを実現します.

14871 ワード

LRUのsetとgetを実現します.
分析とコード
/*
            
        
                     【         ,         】

    :
	hash  +     
	
	hash :	unordered_map::iterator> hashtable
	    :	list<_node> doublelist
	  :
	class _Node{
	public:
		string key;
		int value;
		_Node(string s, int d) :key(s), value(d){}
		~_Node(){ cout << " deconstor _node " << endl; }
	};
	hashtable string _Node string    
	hashtable list<_node>::iterator doublelist    【         ,     】
	
 :
C++ list::splice  list     。  list            ,      list。
         :
void splice ( iterator position, list& x ); 
void splice ( iterator position, list& x, iterator i );
void splice ( iterator position, list& x, iterator first, iterator last );
    : list     :
 x        list     ,           list  x   。
  list      ,             。x              。
                  。      。
              。	
	
*/
class LRU{
public:
	LRU(int s) :size(0), capacity(s){}
	~LRU(){
		for (auto& node : doublelist){
			delete node;
		}
	}
	void set(string s, int d){
		if (hashtable.count(s) == 0){
			if (count() == capcacity()){
				earse(--doublelist.end());
			}
			_Node* temp = new _Node(s, d);
			doublelist.push_front(temp);
			hashtable.insert(make_pair(s, doublelist.begin()));
			++size;
		}
		else{
			(*hashtable[s])->value = d;		
			doublelist.splice(doublelist.begin(), doublelist, hashtable[s]);
		}
	}
	int get(string s){
		if (hashtable.count(s) != 0){
			doublelist.splice(doublelist.begin(), doublelist, hashtable[s]);
			return doublelist.front()->value;
		}
		return INT_MIN;
	}
	void print(){
		for (auto& node : doublelist){
			cout << "key " << node->key << " value " << node->value << endl;
		}
	}
	int count(){
		return size;
	}
	int capcacity(){
		return capacity;
	}
	bool isExistence(string key){
		return (hashtable.count(key) != 0);
	}
private:
	class _Node{
	public:
		string key;
		int value;
		_Node(string s, int d) :key(s), value(d){}
		~_Node(){ cout << " deconstor _node " << endl; }
	};
	unordered_map<string, list<_Node*>::iterator> hashtable;
	list<_Node*> doublelist;
	int size;
	int capacity;
	void earse(list<_Node*>::iterator iter){
		if (iter != doublelist.end()){
			string key = (*iter)->key;
			_Node* del = (*iter);
			doublelist.erase(iter);
			hashtable.erase(key);
			delete del;
			--size;
		}
	}
};
思考
1、保存しかできないint