简体   繁体   English

为什么在 std::deque.erase() 上抛出异常?

[英]Why the exception is thrown on std::deque.erase()?

This throws when trying to remove element from deque via iterator.尝试通过迭代器从deque中删除元素时会抛出此错误。 The error is "can not seek value-initialized iterator" using VS2017.使用 VS2017 的错误是“无法寻找值初始化的迭代器”。 I wonder why this is happening, isn't std::deque a doubly linked list that does not invalidate iterators on push_front() / push_back() ?我想知道为什么会这样, std::deque不是一个不会使push_front() / push_back()上的迭代器无效的双向链表吗?

class deque2 {
public:
    bool enqueue(int val) {
        if (mp.find(val) != mp.end()) {
            return false;
        }
        dq.push_front(val);
        mp[val] = dq.begin();
        return true;
    }

    int dequeue() {
        if (dq.size() == 0) {
            return -1;
        }

        int res = dq.back();
        mp.erase(res);
        dq.pop_back();
        return res;
    }

    void erase(int val) {
        auto it = mp.find(val);
        if (it != mp.end()) {
            dq.erase(it->second); // exception 
            mp.erase(val);
        }
    }
private:
    deque<int> dq;
    unordered_map<int, deque<int>::iterator> mp;
};

isn't std::deque a doubly linked list不是 std::deque 双向链表

No it is not.不它不是。 As stated in documentation文档中所述

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. std::deque(双端队列)是一个索引序列容器,允许在其开头和结尾快速插入和删除。 In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements.此外,在双端队列的任一端插入和删除都不会使指向元素的 rest 的指针或引用无效。

emphasis is mine.重点是我的。 Note that it says that pointer or references not invalidated, not iterators.请注意,它表示指针或引用未失效,而不是迭代器。 And documentations on std::deque::push_front() clearly says so:std::deque::push_front()上的文档清楚地说明了这一点:

All iterators, including the past-the-end iterator, are invalidated.所有迭代器,包括过去的迭代器,都无效。 No references are invalidated.没有引用无效。

As for the logic you are trying to implement I would recommend to use boost::multi_index as it allows single container with different access criteria and you do not have to maintain 2 containers in sync.至于您尝试实现的逻辑,我建议使用boost::multi_index因为它允许具有不同访问条件的单个容器,并且您不必保持 2 个容器同步。 Documentation can be found here文档可以在这里找到

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

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