list1.erase( hash1.find ( p) );没有匹配的函数来调用 'erase' c++

list1.erase( hash1.find ( p) ); no matching function to call 'erase' 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?所以它应该接受iterator erase(const_iterator position)的列表函数调用; ?

我认为 hash1.find 应该 return const_iterator?

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

您可以使用 hash1.find(x)->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[] 不是 return 迭代器,而是对键下映射中值的引用。这意味着无需进一步提取即可直接访问该值。