使用 STL::list 插入和擦除的顺序

the sequence of insert and erase using stl::list

本文关键字:擦除 顺序 插入 STL list 使用      更新时间:2023-10-16

当我在leetcode上练习时,我遇到了这样的问题:

我使用了一个stl::list容器作为 LRU 算法的缓存。但是擦除项目和插入项目的顺序使结果不同。

我知道它实际上是一个双重列表,因为stl::list.当我使用迭代器时,插入和擦除的顺序应该无关紧要。

代码在这里

class LRUCache{
public:
map<int, list<pair<int,int>>::iterator> mKey;
list<pair<int,int>> lCache;
int cap;

LRUCache(int capacity) {
    cap = capacity;
}
int get(int key) {
    auto iter = mKey.find(key);
    if(iter != mKey.end()) {
        int value = (iter->second)->second;

        //**the sequence of next two lines can not be changed!***
        lCache.erase(iter->second);
        mKey[key] = lCache.insert(lCache.begin(), make_pair(key,value));
        return value;
    }
    return -1;
}
void set(int key, int value) {
    auto iter = mKey.find(key);
    if(iter == mKey.end()) {
        if(lCache.size() < cap) {
            mKey[key] = lCache.insert(lCache.begin(), make_pair(key,value));
        }
        else{
            mKey[key] = lCache.insert(lCache.begin(), make_pair(key,value));
            mKey.erase(lCache.back().first);
            lCache.pop_back();
        }
    }
    else {
        lCache.erase(iter->second);
        mKey[key] = lCache.insert(lCache.begin(), make_pair(key,value));
    }
}
};
不太

清楚你在问什么。如果你的问题是为什么这两行不能重新排序:

    //**the sequence of next two lines can not be changed!***
    lCache.erase(iter->second);
    mKey[key] = lCache.insert(lCache.begin(), make_pair(key,value));

那就简单了。 iter指向与mKey[key]相同的节点,因此赋值实际上改变了iter->second的值。如果分配首先发生,则iter->second将指向新插入的列表节点,而不是以前存在的列表节点。