1 定义
//c++98
iterator erase (iterator position);
iterator erase (iterator first, iterator last);
//c++11
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
2 注意
Because vectors use an array as their underlying storage,
erasing elements in positions other than the vector end
causes the container to relocate all the elements
after the segment erased to their new positions.
This is generally an inefficient operation compared to the one
performed for the same operation by other kinds of sequence containers
(such as list or forward_list).
Member types iterator and const_iterator are random access iterator types
that point to elements.
3 返回值
An iterator pointing to the new location of the element
that followed the last element erased by the function call.
This is the container end if the operation erased the last element in the sequence.
4 与map等比较
STL中的容器按存储方式分为两类:
一类是按以数组形式存储的容器(如:vector 、deque);
另一类是以不连续的节点形式存储的容器(如:list、set、map)。
在使用erase方法来删除元素时,需要注意一些问题,以避免引起不可预知错误或崩溃。
在使用 list、set 或 map遍历删除某些元素时可以这样使用
std::list< int> List;
std::list< int>::iterator itList;
for( itList = List.begin(); itList != List.end(); )
{
if( FIND( *itList) )
{
List.erase( itList++);
}
else
++itList;
}
在使用 vector、deque遍历删除元素时,也可以通过erase的返回值来获取下一个元素的位置:
std::vector< int> Vec;
std::vector< int>::iterator itVec;
for( itVec = Vec.begin(); itVec != Vec.end(); )
{
if( FIND( *itVec) )
{
itVec = Vec.erase( itVec);
}
else
++itList;
}
参考文献:
[1]http://www.cplusplus.com/reference/vector/vector/erase/
[2]http://blog.sina.com.cn/s/blog_508938e10101gnw0.html 作者:大树叶