The LRU cache is implemented in the stout. The cache members are as follows:
Public : typedef std::list<Key> list; typedef STD::TR1::UNORDERED_MAP< Key, std::p air<value, TypeName list::iterator> > map;
You can see that the second item in the map, in addition to value, has an iterator to key, which is designed to improve the efficiency of the cache LRU operation: When querying a key, it also obtains the value and key iterator in the list. It is convenient to swap the key with the last element in the IST, as follows:
void Use (const TypeName map::iterator& i) { // Move the ' pointer ' To the end of the LRU list. Keys.splice (Keys.end (), Keys, (*i). Second.second); // Now update the "pointer" so we can do this again. (*i). Second.second =--keys.end (); }
Here the List.splice is used to exchange the position of two elements. The usage of splice is as follows:
#include <list><iostream><algorithm>int main () { std::list <int> A = {ten10000}; For_each (Begin (a), end (a), [] (int n) {std::cout << n << Std::endl;}); A.splice (End (a), A, Begin (a)); For_each (Begin (a), end (a), [] (int n) {std::cout << n << Std::endl;}); return 0;
For the use of LRU cache, the sample code is as follows:
#include"stout/cache.hpp"#include<iostream>#include<string>intMain () {Cache<int, std::string> A (3); A.put (1," One"); A.put (2," Both"); A.put (3,"three"); Std::cout<< a <<Std::endl; A.Get(2); Std::cout<< a <<Std::endl; A.put (4," Four"); Std::cout<< a <<Std::endl; return 0;}
Note: A compilation error was found in the cache overload << operator during use,
Template <typename Key, TypeName value>Std::ostream&operator<<(Std::ostream&Stream,ConstCache<key, value>&c) {TypeName Cache<key, value>:: List::const_iterator i1; for(I1 = C.keys.begin (); I1! = C.keys.end (); i1++) {Stream<< *i1 <<": "; TypeName Cache<key, value>:: Map::const_iterator i2; I2= C.values.find (*i1); CHECK (I2!=c.values.end ()); Stream<< *i2 <<Std::endl; } returnstream;}
Workaround: Place the third line
Stream << *i2 << Std::endl;
Change into
Stream << I2->second.first << Std::endl;
Can.
Stout Code Analysis Eight: the Cache class