How to dereference a pointer to a list's node from a map in C++? (LRU Cache)

135 Views Asked by At

Minimum reproducible example here: https://repl.it/@amejiarosario/lrc-cachecpp

I'm implementing an LRU cache on C++ using unordered_map and doubly linked list. Each linked list node is an array [key, value]. The HashMap takes an integer as a key and the value is a pointer/iterator to a Node in the linked list:

class LRUCache {
  int max;
  list<vector<int, int>> kvList;
  unordered_map<int, decltype(kvList)::iterator> lmap;
public:
  LRUCache(int capacity): max(capacity) {}

  int get(int key) {
    auto it = lmap.find(key);
    if (it == lmap.end()) return -1;
    put(key, (*it->second)[0]);
    return (*it->second)[0];
  }

  void put(int key, int value) {
    kvList.push_back({ key, value });
    if (lmap.find(key) != lmap.end()) kvList.erase(lmap.at(key));
    lmap[key] = prev(kvList.end());
  }
};

I'm having some issues running this code. When I initialize it like

LRUCache *lRUCache = new LRUCache(2);

I get the following error:

clang++-7 -pthread -std=c++17 -o main main.cpp
In file included from main.cpp:1:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/list:63:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_list.h:60:
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/ext/alloc_traits.h:49:47: error: 
      type 'int' cannot be used prior to '::' because it has no members
template<typename _Alloc, typename = typename _Alloc::value_type>
                                              ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:83:35: note: 
      in instantiation of default argument for '__alloc_traits<int>' required
      here
      typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
                                  ^~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:339:30: note: 
      in instantiation of template class 'std::_Vector_base<int, int>'
      requested here
    class vector : protected _Vector_base<_Tp, _Alloc>
                             ^
main.cpp:16:12: note: in instantiation of template class
      'std::vector<int, int>' requested here
    if (it == lmap.end()) return -1;

What's wrong with the if (it == lmap.end()) return -1;?

0

There are 0 best solutions below