矢量擦除不会"erase"第一个元素

Vector erase will not "erase" first element

本文关键字:erase 元素 第一个 擦除      更新时间:2023-10-16

编辑器是vector::迭代器对象,list显然是vector。

我想知道为什么它不会(vector).erase()列表的第一个元素,当我尝试只使用一个项目时,它会抛出异常。

for (editor = list.begin(); editor < list.end(); ++editor)
    if (*editor == title)           
        list.erase(editor);

更喜欢算法而不是手写循环。只要这样做,就不会有任何担心:

list.erase(std::remove(list.begin(), list.end(), title), list.end());

注:另外,我强烈建议不要将对象命名为STD类型(list是STD::类型),甚至不要将它们命名为与不同的容器类型匹配。

在迭代vector对象时进行擦除操作并不像看上去那么简单,可能会导致迭代器失效。

不使迭代器失效的正确方法是:

editor = list.begin();
while (editor < list.end()) {
    if (*editor == title)
        list.erase(editor++);
    else
        ++editor;
}

这可确保在擦除元素时迭代器不会失效。

注意,operator++向前移动迭代器,但返回先前要删除的迭代器位置(即您想要删除的位置)。

在某些星座也可以使用std::removestd::remove_if

查看这个问题了解更多信息:Std::vector iterator invalidation

问题不在于擦除;问题是您希望在之后使用相同的迭代器(用于与end()的比较)。如果在擦除元素后立即将breakfor循环中取出,则可以工作。

你确定这是第一个,而不是后面的?

在对vector进行erase突变之后,所有迭代器都无效(包括end),因此必须重新构建每个迭代器,或者在擦除某些内容后立即中断并退出循环。

for (editor = list.begin(); editor < list.end(); ++editor)
{
    if ( *editor == title )
    {
        size_t pos = editor - list.begin() ; // here's where we are now
        list.erase ( editor ) ;
        editor = list.begin() + pos ; // rebuild the iterator
    }
}

for (editor = list.begin(); editor < list.end(); ++editor)
{
    if ( *editor == title )
    {
        list.erase ( editor ) ;
        break ; // stop iterating
    }
}