矢量擦除不会"erase"第一个元素
Vector erase will not "erase" first element
编辑器是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::remove
和std::remove_if
。
查看这个问题了解更多信息:Std::vector iterator invalidation
问题不在于擦除;问题是您希望在之后使用相同的迭代器(用于与end()
的比较)。如果在擦除元素后立即将break
从for
循环中取出,则可以工作。
你确定这是第一个,而不是后面的?
在对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
}
}
相关文章:
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ Map erase(),迭代器打印 erased 元素
- 使用 str.erase() 的索引擦除字符串的元素?
- 为什么 vector::erase 不能在带有 const 的类元素上工作
- C++ STL 中的 erase() 真的会删除元素吗?
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- vector.erase-它总是删除我的最后一个元素
- std::erase 和 std::remove 组合以删除特定元素不适用于特定示例
- std::vector::erase删除最后一个元素而不是第一个元素
- 我读了map.erase(map.end());删除地图的最后一个元素。但是最后一个元素是什么?它是否基于元素的插入顺序?
- 使用 std::erase 和 std::remove 从矢量中删除元素,不使用自定义结构作为值
- std::set 在使用 std::set.erase 后包含重复元素
- vector::erase不会擦除所需的元素,而是从向量中擦除最后一个元素
- unordered_set::erase(pos)是否保留元素的顺序?
- c++ STL vector.erase()总是删除最后一个元素
- 为什么在调用erase和push_back函数后,下列元素同时出现在这个c++ vector的头和尾?
- 矢量擦除不会"erase"第一个元素
- erase删除迭代器所指向的元素失败时的处理方法
- Vector pop_back、erase和clear不会破坏Vector的元素