简体   繁体   English

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

[英]the sequence of insert and erase using stl::list

When I am doing practice on leetcode, I met a problem like this: 当我在leetcode上练习时,遇到了这样的问题:

I used a stl::list container as cache for LRU algorithm. 我使用了stl::list容器作为LRU算法的缓存。 But the sequence of erasing an item and inserting an item made the result different. 但是擦除项目和插入项目的顺序使结果有所不同。

I know that it is actually a double list as stl::list . 我知道这实际上是stl::list的双重stl::list And the sequence of inserting and erasing should not matter when I use iterator. 当我使用迭代器时,插入和擦除的顺序应该无关紧要。

The code is here 代码在这里

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));
    }

}
};

It's not quite clear what you are asking. 您要问的还不太清楚。 If your question is why these two lines can't be reordered: 如果您的问题是为什么不能重新排列这两行:

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

then that's simple. 那很简单。 iter points to the same node as mKey[key] , so the assignment actually changes the value of iter->second . iter指向与mKey[key]相同的节点,因此分配实际上更改了mKey[key] iter->second的值。 If the assignment would happen first, then iter->second would point to the freshly inserted list node, not the previously existing one. 如果分配首先发生,则iter->second将指向新插入的列表节点,而不是先前存在的列表节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM