Please have a look at my code sample. I am trying to create a LRUCache class to manage least recent cache. I am facing some vector errors in unexpected places. I do not know why I am having problems with vector v in my class. It is just a member variable inside my class:
..\src\lru.cpp: In instantiation of 'void LRUCache<K, V>::put(K, V) [with K
= int; V = int]':
..\src\lru.cpp:70:20: required from here
..\src\lru.cpp:57:20: error: request for member 'size' in 'v', which is of
non-class type 'int'
if(capacity == v.size()) { // vector v is full
~~^~~~
Here is my code:
template <class K, class V>
class LRUCache {
private:
int capacity;
vector<K> v;
unordered_map<K, V> m;
int findIndexOfK(K k);
public:
LRUCache(int vcapacity) : capacity(vcapacity) {
}
V get(K k);
void put(K k, V v);
};
template <class K, class V>
int LRUCache<K, V>::findIndexOfK(K k) {
int index {-1};
for(int i=0; i < capacity; i++) {
if(v[i]==k) {
index = i;
break;
}
}
return index;
}
template <class K, class V>
V LRUCache<K, V>::get(K k) {
auto i = m.find(k);
if(i == m.end()) {
return -1;
}
else
return i->second;
}
template <class K, class V>
void LRUCache<K, V>::put(K k, V v) {
int index = findIndexOfK(k);
if(index == -1) {
if(capacity == v.size()) { // vector v is full
v.erase(v.begin()); // Remove the least recent one
}
}
else {
v.erase(v.begin()+index); // Remove the existing one whose index was found
}
m[k] = v;
v.add(k);
}
int main() {
LRUCache<int, int> lrucache(3);
lrucache.put(2, 33);
lrucache.put(5, 40);
assert(lrucache.get(2) == 33);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire