Excaliburer`s Zone

It was challenging, but not risky.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

erase()是STL提供的容器中比较常用的方法之一,它的功能是删除容器中的某些元素,其中它的函数原型如下:

1.有两个参数,且参数类型都是size_t型:

string& erase ( size_t pos = 0, size_t n = npos );

功能是:删除容器中从pos位置开始的n个元素。返回值是经过删除操作后的容器。

示例:

#include<iostream>
using namespace std;

int main()
{
    string str = "hello world!";
    string::iterator it_1 = str.begin();
    string::iterator it_2 = str.begin() + 1;
    //用法1
    cout<<str.erase(0,1)<<endl;
}

结果:

(注:第一种erase用法是string容器所特有的,vectro和list等容器没有这种用法,更多erase的用法见http://www.cplusplus.com/search.do?q=erase)

2.有一个参数,且参数类型为iterator:

iterator erase ( iterator position );

功能是:删除容器中position所指位置的元素。返回值是指向被删元素之后的那个元素(即下一个元素)的迭代器。

示例:

#include<iostream>
using namespace std;

int main()
{
    string str = "hello world!";
    string::iterator it_1 = str.begin();
    string::iterator it_2 = str.begin() + 1;
    //用法2
    str.erase(it_1);
    cout<<str<<endl;
}

结果:

3.有两个参数,且参数类型都是iterator:

iterator erase ( iterator first, iterator last );

功能是:删除容器中first到last之间的所有元素(左闭右开),但不包括last所指的元素。(即删除fist~last -1所指的元素)返回值是一个迭代器,该迭代器指向last所指得的元素,可以理解为返回的就是last。

示例:

#include<iostream>
using namespace std;

int main()
{
    string str = "hello world!";
    string::iterator it_1 = str.begin();
    string::iterator it_2 = str.begin() + 1;
    //用法3
    str.erase(it_1,it_2);
    cout<<str<<endl;
}

结果:

 

posted on 2018-05-11 12:52  Excaliburer  阅读(13701)  评论(0编辑  收藏  举报