为什么引发此断言失败警报的向量

why is the vector throwing this assertion failed alert?

本文关键字:向量 失败 断言 为什么      更新时间:2023-10-16

我在调试模式下运行我的代码,程序弹出断言失败消息。请帮我找到导致此断言失败的部分。:{

Debug Assertion Failed!
Expression: vector iterators incompatible

法典:

int main()
{
vector<int> a(5);
fill(a.begin(), a.end(), 5);
a[2] = 3;
a[1] = 2;  //so now a = {5,2,3,5,5} 
auto it = a.begin();
for (; it != a.end();)
{
    if (*it == 5)
        a.erase(it);  //Remove 5
    else
        it++;
}
copy(a.begin(), a.end(), ostream_iterator<int>(cout, "n"));
}

在迭代过程中擦除时,擦除的迭代器将变为(其他迭代器可能变为)无效:

来得及:

它 = a.erase(it);