Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <unordered_map>
- #include <string>
- template<typename T, typename U>
- struct custom_cache{
- struct Node {
- Node() = default;
- Node(T key, U value) : key(key), value(value) {}
- T key;
- U value;
- Node* next = nullptr;
- Node* prev = nullptr;
- };
- unsigned int N = 0;
- unsigned int amount = 0;
- custom_cache(unsigned int N) : N(N) {}
- std::unordered_map<T, Node*> addresses;
- Node* begin = nullptr;
- Node* end = nullptr;
- U get(T key) {
- if (!begin || !end || addresses.count(key) == 0) {
- return NULL;
- }
- if (addresses[key]->next) {
- addresses[key]->next->prev = addresses[key]->prev;
- }
- if (addresses[key]->prev) {
- addresses[key]->prev->next = addresses[key]->next;
- }
- begin->next = addresses[key];
- addresses[key]->next = nullptr;
- addresses[key]->prev = begin;
- begin = addresses[key];
- return begin->value;
- }
- void put(T key, U value) {
- if (addresses.count(key) != 0) {
- return;
- }
- amount++;
- auto node = new Node(key, value);
- addresses[key] = node;
- if (!begin || !end) {
- begin = end = node;
- } else {
- node->prev = begin;
- begin->next = node;
- begin = node;
- if (amount > N) {
- amount = N;
- addresses[end->key] = end->next->prev = nullptr;
- delete end->next->prev;
- end = end->next;
- }
- }
- }
- void printList() {
- auto node = begin;
- while (node) {
- std::cout << node->key << ' ' << node->value << '\n';
- node = node->prev;
- }
- }
- };
- void getAll(custom_cache<int, std::string>* cache) {
- std::cout << cache->get(3) << ' ';
- std::cout << cache->get(4) << ' ';
- std::cout << cache->get(5) << '\n';
- }
- void test1() {
- int a = 3, b = 4, c = 5;
- std::string s1 = "a", s2 = "b", s3 = "c";
- auto cache = custom_cache<int, std::string>(3);
- cache.put(a, s1);
- cache.put(b, s2);
- cache.put(c, s3);
- getAll(&cache);
- cache.printList();
- }
- void test2() {
- int a = 3, b = 4, c = 5;
- std::string s1 = "a", s2 = "b", s3 = "c";
- auto cache = custom_cache<int, std::string>(2);
- cache.put(a, s1);
- cache.put(b, s2);
- cache.put(c, s3);
- cache.printList();
- }
- void test3() {
- int a = 3, b = 4, c = 5;
- std::string s1 = "a", s2 = "b", s3 = "c";
- auto cache = custom_cache<int, std::string>(1);
- cache.put(a, s1);
- cache.put(b, s2);
- cache.put(c, s3);
- cache.printList();
- }
- int main() {
- test1();
- std::cout << "\n\n";
- test2();
- std::cout << "\n\n";
- test3();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement