0

I am working on implementing LRU Cache based on a LeetCode exercise, but the following code does not compile

using namespace std;

class LRUCache {
private:
    list<int> data;
    unordered_map<int, list<int>::iterator&> keys_to_data;

    void update_recency(int key, list<int>::iterator& it) {
        data.erase(it);
        data.push_front(key);
        keys_to_data[key]; // issue here
    }
public:
    LRUCache(int capacity) {

    }

    int get(int key) {
        int value = -1;
        auto value_it = keys_to_data.find(key);
        if(value_it != keys_to_data.end()) {
            value = *(value_it->second);
            update_recency(key, value_it->second);
        }
        return value;
    }

    void put(int key, int value) {
    }
};

/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:1360:7: error: reference to type 'std::__1::__list_iterator' requires an initializer second(_VSTD::forward<_Args2>(_VSTD::get<_I2>(__second_args))...) ^

... huge stacktrace ...

/Users/Paul/Desktop/int/main.cpp:17:21: note: in instantiation of member function 'std::__1::unordered_map &, std::__1::hash, std::__1::equal_to, std::__1::allocator &> > >::operator[]' requested here keys_to_data[key];

Oblivion
  • 7,176
  • 2
  • 14
  • 33
Paul
  • 55
  • 5

2 Answers2

5

You cannot store a reference as value in your map

unordered_map<int, list<int>::iterator&>

As the reference is not assignable.

Oblivion
  • 7,176
  • 2
  • 14
  • 33
0

Storage the iterator, not a reference to the iterator

unordered_map::iterator> keys_to_data;

Mike
  • 693
  • 3
  • 13