首页 > 解决方案 > list1.erase(hash1.find (p)); 没有匹配的函数来调用“擦除”C++

问题描述

为什么它不接受 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?

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

解决方案


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

您可以使用以下方法在迭代器下检索 map 中的值hash1.find(x)->second

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[]另一方面,不返回迭代器,而是对键下映射中值的引用。这意味着无需进一步提取即可直接访问该值。


推荐阅读