【问题标题】:How to fix 'reference to type requires an initializer'?如何修复“对类型的引用需要初始化程序”?
【发布时间】: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&lt;int, list&lt;int&gt;::iterator&amp;&gt; 中的迭代器的理由?
  • (如果不清楚:您不能将引用用作地图值。)
  • 这里可能的答案:stackoverflow.com/questions/922360/…

标签: c++ c++11 unordered-map


【解决方案1】:

您不能将引用作为值存储在地图中

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

因为引用不可分配。

【讨论】:

    【解决方案2】:

    存储迭代器,而不是对迭代器的引用

    unordered_map::iterator> keys_to_data;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      相关资源
      最近更新 更多