vector iterators incompatible问题

来源:互联网 发布:新郎新婚致辞 知乎 编辑:程序博客网 时间:2024/05/22 14:16

今天写删除vector元素出现vector iterators incompatible



的问题:

代码如下:

vector<int> v;

...

auto end = v.end();

auto iter = v.begin();


while(iter != end)

{

v.erase(iter);

}

出现上述问题

第一轮解决:

while(iter != end)

{

iter = v.erase(iter);

}

测试,仍旧出现上述问题。

最后F11进入微软代码发现

void _Compat(const _Myiter& _Right) const

        {    // test for compatible iterator pair
        if (this->_Getcont() == 0
            || this->_Getcont() != _Right._Getcont())
            {    // report error
            _DEBUG_ERROR("vector iterators incompatible");
            _SCL_SECURE_INVALID_ARGUMENT;
            }

        }

上述代码表明两个数量不等。删除元素后造成end迭代器的位置发生变化

第二轮解决:

while(iter != v.end())

{

iter = v.erase(iter);

}

测试OK!

0 0
原创粉丝点击