std::vector::erase()

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中的容器按存储方式分为两类:
一类是按以数组形式存储的容器(如:vectordeque); 
另一类是以不连续的节点形式存储的容器(如:listsetmap)。
在使用erase方法来删除元素时,需要注意一些问题,以避免引起不可预知错误或崩溃。



      在使用 listsetmap遍历删除某些元素时可以这样使用
      std::list< int> List;
      std::list< int>::iterator itList;
      for( itList = List.begin(); itList != List.end(); )
      {
            if( FIND( *itList) )
            {
               List.erase( itList++);
            }
            else
               ++itList;
      }


      在使用 vectordeque遍历删除元素时,也可以通过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 作者:大树叶

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值