【发布时间】:2020-02-15 15:19:57
【问题描述】:
我正在根据 LeetCode 练习实现 LRU Cache,但以下代码无法编译
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:错误:对类型“std::__1::__list_iterator”的引用需要初始化程序 第二(_VSTD::forward<_args2>(_VSTD::get<_i2>(__second_args))...) ^
...巨大的堆栈跟踪...
/Users/Paul/Desktop/int/main.cpp:17:21: 注意:在成员函数 'std::__1::unordered_map &, std::__1::hash, std::__1 的实例化中: :equal_to, std::__1::allocator &> > >::operator[]' 在这里请求 keys_to_data[key];
【问题讨论】:
-
您能否分享一下您为什么需要引用
unordered_map<int, list<int>::iterator&>中的迭代器的理由? -
(如果不清楚:您不能将引用用作地图值。)
标签: c++ c++11 unordered-map