【问题标题】:list1.erase( hash1.find ( p) ); no matching function to call 'erase' c++list1.erase(hash1.find (p));没有匹配的函数来调用“擦除”C++
【发布时间】:2019-08-18 10:00:06
【问题描述】:

为什么它不接受 hash1.find(p) 但如果我使用 hash1[p] 可以找到?

class LRUCACHE {
    list<int> list1;   // store keys of Cache.

    unordered_map<int, list<int>::const_iterator> hash1;     // Store reference of Keys in Cache.
    int maxsize;

public:
    LRUCACHE(int);
    void set(int);
    void get(int);
};

LRUCACHE::LRUCACHE(int n) {    
    maxsize = n;
}


void LRUCACHE::get(int x) {
    // Not Found in Cache.
    if (hash1.find(x) == hash1.end() ) {

        // if Max size.
        if (list1.size() == maxsize ) {

            // returns the last element of LIST.
            int last = list1.back();

            // Remove last element of LIST and reduce size by 1.
            list1.pop_back();

            hash1.erase(last); 
        }
    }
    else {
        list1.erase(hash1[x]);
    }
    list1.push_front(x);
    hash1[x] = list1.begin(); // points and updates.
}

void LRUCACHE::get(int p) {
    if (hash1.find(p) == hash1.end() ){
        cout << "not found " << endl;
    }
    else {
        list1.erase(hash1.find(p)); // Error Here member function not found
    }
}

我认为我将 const_iterator 用于 unordermap?所以它应该接受它列出迭代器擦除(const_iterator position)的函数调用; ?

我认为 hash1.find 应该返回 const_iterator?

【问题讨论】:

  • hash1[p] 将为键 p 创建一个键值对(如果它不存在)。

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


【解决方案1】:

std::unordered_map::find() 返回一个迭代器,而不是映射中的值。所以你得到的是std::unordered_map&lt;int, std::list&lt;int&gt;::const_iterator&gt;&gt;::iterator(或std::unordered_map&lt;int, std::list&lt;int&gt;::const_iterator&gt;&gt;::const_iterator

您可以使用hash1.find(x)-&gt;second检索迭代器下map中的值:

void LRUCACHE::get(int p) {
    const auto iter = hash1.find(p);
    if (iter == hash1.end() ){
        cout << "not found " << endl;
    } else {
        list1.erase(iter->second); 
    }
}

std::unordered_map::operator[] 另一方面不返回迭代器,而是对键下映射中值的引用。这意味着无需进一步提取即可直接访问该值。

【讨论】:

  • 哦,我以为 std::unordered_map::find() 可以返回 const_iterator 迭代器查找( const key_type& k ); const_iterator find ( const key_type& k ) const;
  • @Kenny 可以。但它是std::unordered_map 的迭代器,而不是您存储在地图中的std::list 的迭代器
猜你喜欢
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多