Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<map>
- #include<sstream>
- using namespace std;
- struct node {
- node* prev;
- node* next;
- int val, key;
- node(node* prev=nullptr,node* next=nullptr,int key=NULL,int val=NULL)
- :prev{ prev }, next{ next }, val{ val }, key{ key } {}
- };
- struct cache {
- int cp;
- node* head;
- node* tail;
- map<int, node*> mp;
- cache(int capacity = NULL) : cp(capacity), head{ nullptr }, tail{ nullptr }{}
- void set(int key, int val) {
- auto f = mp.find(key);
- if (f != mp.end()) { mp[key]->val = val; moveToTail(mp[key]); }
- else if (mp.size() < cp) {
- if (!head) {
- head = new node(nullptr, nullptr, key, val);
- mp[key] = head;
- }
- else if (!tail) {
- tail = new node(head, head, key, val);
- head->next = tail;
- head->prev = tail;
- mp[key] = tail;
- }
- else {
- node* n = new node(tail, head, key, val);
- tail->next = n;
- tail = n;
- head->prev=n;
- mp[key] = n;
- }//probably need a scenario where cp is only 1... but im not doing it...
- }
- else { //capacity is reached....shift head to the rear
- auto f = mp.find(head->key);
- mp.erase(f);
- tail = head;
- head = tail->next;
- tail->key = key;
- tail->val = val;
- mp[key] = tail;
- }
- }
- void moveToTail(node* n) {
- if (n == tail) { return; }
- else if (n == head) {
- tail = head;
- head = tail->next;
- }
- else {
- n->prev->next = n->next; //removes itself from old positiion
- n->next->prev = n->prev;
- n->next = head; //inserts itself in new postion
- n->prev = tail;
- tail->next = n; //updates the nodes on both sides
- head->prev = n;
- tail = n; //updates the tail
- }
- }
- int get(int key) { //push newest hits to the back
- auto f = mp.find(key);
- if (f == mp.end()) { return -1; }
- moveToTail(mp[key]);
- return tail->val;
- }
- void printptrs() {
- for (auto& n : mp) {
- cout << " prev = " << n.second->prev << " current = " << n.second << " next = " << n.second->next << "\n";
- }
- }
- void printMap() {
- for (auto& m : mp) {
- cout << "key = " << m.first << " val = " << m.second->val << "\n";
- }
- }
- void printMapOrdered() {
- node* n = head;
- do {
- cout << "key = " << n->key << " val = " << n->val << "\n";
- n = n->next;
- } while (n != head);
- }
- };
- int main()
- {
- stringstream ss;
- ss << "4 0 1 2 3 4 5 6 7 8 9"; //simple test case
- int n,k,v;
- ss >> n;
- cache c(n);
- while(ss>>k>>v){
- c.set(k, v);
- //printptrs();
- }
- c.get(4);
- c.printMap();
- cout << " \n\n";
- c.printMapOrdered();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement