13 #ifndef __STOUT_CACHE_HPP__ 14 #define __STOUT_CACHE_HPP__ 20 #include <unordered_map> 23 #include <glog/logging.h> 29 template <
typename Key,
typename Value>
33 template <
typename Key,
typename Value>
34 std::ostream& operator<<(std::ostream& stream, const Cache<Key, Value>& c);
39 template <
typename Key,
typename Value>
43 typedef std::list<Key>
list;
44 typedef std::unordered_map<
45 Key, std::pair<Value, typename list::iterator>>
map;
47 explicit Cache(
size_t _capacity) : capacity(_capacity) {}
49 void put(
const Key& key,
const Value& value)
51 typename map::iterator i = values.find(key);
52 if (i == values.end()) {
55 (*i).second.first = value;
62 typename map::iterator i = values.find(key);
64 if (i != values.end()) {
66 return (*i).second.first;
74 typename map::iterator i = values.find(key);
76 if (i != values.end()) {
77 Value value = i->second.first;
78 keys.erase(i->second.second);
86 size_t size()
const {
return keys.size(); }
94 friend std::ostream& operator<<<>(
99 void insert(
const Key& key,
const Value& value)
101 if (keys.size() == capacity) {
106 typename list::iterator i = keys.insert(keys.end(), key);
109 values.insert(std::make_pair(key, std::make_pair(value, i)));
113 void use(
const typename map::iterator& i)
116 keys.splice(keys.end(), keys, (*i).second.second);
119 (*i).second.second = --keys.end();
125 const typename map::iterator i = values.find(keys.front());
126 CHECK(i != values.end());
132 const size_t capacity;
142 template <
typename Key,
typename Value>
143 std::ostream& operator<<(std::ostream& stream, const Cache<Key, Value>& c)
146 for (i1 = c.keys.begin(); i1 != c.keys.end(); i1++) {
147 stream << *i1 <<
": ";
149 i2 = c.values.find(*i1);
150 CHECK(i2 != c.values.end());
151 stream << *i2 << std::endl;
156 #endif // __STOUT_CACHE_HPP__ Definition: option.hpp:29
std::list< Key > list
Definition: cache.hpp:43
size_t size() const
Definition: cache.hpp:86
void put(const Key &key, const Value &value)
Definition: cache.hpp:49
std::unordered_map< Key, std::pair< Value, typename list::iterator > > map
Definition: cache.hpp:45
Option< Value > erase(const Key &key)
Definition: cache.hpp:72
Cache(size_t _capacity)
Definition: cache.hpp:47