如何修复 'reference to type requires an initializer'?
How to fix 'reference to type requires an initializer'?
我正在基于 LeetCode 练习实现 LRU 缓存,但以下代码无法编译
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[键];
您不能将引用存储为地图中的值
unordered_map<int, list<int>::iterator&>
因为引用不可分配。
存储迭代器,而不是对迭代器的引用
unordered_map::迭代器> keys_to_data;
我正在基于 LeetCode 练习实现 LRU 缓存,但以下代码无法编译
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[键];
您不能将引用存储为地图中的值
unordered_map<int, list<int>::iterator&>
因为引用不可分配。
存储迭代器,而不是对迭代器的引用
unordered_map::迭代器> keys_to_data;