内容:
说明:
特定数量键值对,超过数量,最后的替换最开始的
示例代码:
// AbstractClasses-Polymorphism.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <map> #include <iostream> using namespace std; struct Node { Node* next; Node* prev; int value; int key; Node( Node* p, Node* n, int k, int val ) : prev( p ), next( n ), key( k ), value( val ) {}; Node( int k, int val ) : prev( NULL ), next( NULL ), key( k ), value( val ) {}; }; class Cache { protected: map<int, Node*> mp; //map the key to the node in the linked list int cp; //capacity Node* tail; // double linked list tail pointer Node* head; // double linked list head pointer virtual void set( int, int ) = 0; //set function virtual int get( int ) = 0; //get function }; class LRUCache : public Cache { public: //the max size in map LRUCache( int num ) { this->cp = num; tail = NULL; head = NULL; } void set( int key, int value ) { //first key if( head == NULL ) { mp[key] = new Node( key, value ); head = mp[key]; tail = head; } else { //over the size,pre instead oldest if( mp.size() >= this->cp ) { Node* cur = tail->prev; int dKey = tail->key; mp.erase( dKey ); tail = cur; } //insert else { mp[key] = new Node( NULL, tail, key, value ); head = mp[key]; head->next->prev = head; } } } int get( int key ) { if( mp.find( key ) != mp.end() ) { return mp[key]->value; } else { return -1; } } private: }; //by zhaocl int main() { int n, m; cin >> n >> m; LRUCache mc( m ); for( int i = 0; i < n; i++ ) { string cmd; cin >> cmd; if( !cmd.compare( "get" ) ) { int key; cin >> key; cout << mc.get( key ) << endl; } else if( !cmd.compare( "set" ) ) { int key, value; cin >> key >> value; mc.set( key, value ); } } system( "pause" ); return 0; }
知识点:
1、多态的简单应用:名字相同、参数不同
2、纯虚函数的实现