Last active
August 29, 2015 14:07
-
-
Save Youka/6c20aa5dbf5f650e334b to your computer and use it in GitHub Desktop.
Cache for pairs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <deque> | |
| #include <algorithm> | |
| template<typename Key, typename Value> | |
| class Cache{ | |
| private: | |
| std::deque<std::pair<Key,Value>> data; | |
| const unsigned int max_size; | |
| public: | |
| Cache(unsigned int max_size = 64) : max_size(max_size){} | |
| bool contains(Key key){ | |
| return std::find_if(this->data.begin(), this->data.end(), [&key](std::pair<Key,Value>& entry){ | |
| return entry.first == key; | |
| }) != this->data.end(); | |
| } | |
| Value get(Key key){ | |
| auto it = std::find_if(this->data.begin(), this->data.end(), [&key](std::pair<Key,Value>& entry){ | |
| return entry.first == key; | |
| }); | |
| if(it != this->data.end()){ | |
| auto elem = *it; | |
| this->data.erase(it); | |
| this->data.push_front(elem); | |
| return elem.second; | |
| }else | |
| return Value(); | |
| } | |
| void add(Key key, Value value){ | |
| this->data.push_front({key, value}); | |
| if(this->data.size() > this->max_size) | |
| this->data.pop_back(); | |
| } | |
| void clear(){ | |
| this->data.clear(); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment