C++(11):erase函数

前面的文章中提到过如何向容器中添加元素,这里介绍一个如何删除容器中元素的函数,包括顺序容器和关联容器。

就是这个erase函数,基本用法如下:

c.erase(k)------------------------------从c中删除元素k,返回一个size_type值,指出删除的元素的数量

c.erase(p)------------------------------从c中删除迭代器p指定的元素,p必须指向c中的一个真实元素,不能等于c.end()

c.erase(b,e)----------------------------从c中删除迭代器对b和e所表示的范围中的元素,返回e

具体用法如下:

vector<string> c = {"a","b","c","d","e"};
e.erase("c");        //删除字符串“c”
auto it = e.end();    
e.erase(it);           //删除末尾元素“e”
auto it2 = e.begin();
auto it3 = e.end();
e.erase(it2,it3);    //删除it2到it3之间的元素

对于第三种用法,可以拓展一下:

auto it = a.begin();
auto it2 = a.find("c");        //it2指向“c”所在位置
auto it3 = a.erase(it,it2);    //删除it到it2之间的所有元素,即“a”和“b”
a.erase(it3);                  //此时删除的是“c”,即先前it2所指,因为第三种用法返回的就是第二个迭代器所指位置

猜你喜欢

转载自blog.csdn.net/Leo_csdn_/article/details/82221721