彻底掌握erase函数

今天又遇到erase问题,以前存在着一些疑惑,今天决定将其彻底弄清楚,首先看看函数的声明:
#include <list>
iterator erase( iterator loc );
iterator erase( iterator start, iterator end );

The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end). The return value is the element after the last element erased.
这上面的最后一句话,我觉得不好理解,既然这样就只有看源代码了。

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always

takes linear time.

源码如下:
  iterator erase(iterator __position)
 {
    if (__position + 1 != end())
      copy(__position + 1, _M_finish, __position); //首先这里把后面的元素向前移动一个单位,覆盖要删
除的元素.
    --_M_finish;
    destroy(_M_finish); //释放最后一个元素占据的存储空间
    return __position; //这里返回的位置已经是删除元素的下一个的位置
  }
  iterator erase(iterator __first, iterator __last)
  {
    iterator __i = copy(__last, _M_finish, __first);
    destroy(__i, _M_finish);
    _M_finish = _M_finish - (__last - __first);
    return __first;
  }

我想大家如果看了源代码,就很好理解erase的工作原理了,最后附上一道简单测试题目,源于C++primer(The third Edition),我给出一个简单的解决方案。

/*
请写一个程序使它接受下列定义
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
list<int> ilist( ia, ia+11 );
用单个iterator 形式的erase()删除ilist 中所有奇数位置的元素
*/
#include<iostream>
#include<list>
using namespace std;

int main()
{
    int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
    int ia_size = sizeof(ia) / sizeof(int);
    list<int> ilist(&ia[0],&ia[ia_size]);
   
    list<int>::iterator ite;
    for(ite = ilist.begin();ite != ilist.end();++ite)
    {
        cout<<*ite<<"   ";
    }
    cout<<endl;
   
    // do earse operation
    list<int>::iterator tmpite;
    int iIndex = 1; //记录元素的位置
    for(ite = ilist.begin();ite != ilist.end();++ite)
    {
       if(iIndex % 2 == 1)
       {
               ite = ilist.erase(ite); //这里ite已经失效,所以需要保存返回值
               --ite;   //这里--操作,以抵消++操作,这样才能不遗漏元素而遍历完所有的元素了.
       }
       ++iIndex;
    }
    for(ite = ilist.begin();ite != ilist.end();++ite)
    {
        cout<<*ite<<"   ";
    }
    cout<<endl;
    system("pause");
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值