iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
从vector中删除一个元素(position),或者范围元素( [first, last) )
参数:
position :iterator 指向vector 中要删除元素的位置。
iterator first,last :iterator指向要删除范围。
position
Iterator pointing to a single element to be removed from the vector.
Member types iterator and const_iterator are random access iterator types that point to elements.
first, last
Iterators specifying a range within the vector] to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
Member types iterator and const_iterator are random access iterator types that point to elements.
返回值:
返回一个iterator ,指向删除元素的下一个元素。所以在用for循环删除元素时,迭代器不用++指向下一个元素,erase()执行后,自动返回一个迭代器指向下一个元素。
例子:
#include<vector>
#include<iostream>
int main()
{
vector<int> myvector;
for(int i=0;i<20;i++)
{
myvector.push_back(i);
}
myvector.erase(myvector.begin()+2);//删除第三个元素
myvecotr.erase(myvector.begin(),myvector.bengin()+3);//删除前3个元素,[ .. ),第四个元素没有删除
for(auto it=myvector.begin();it!=myvecotr.begin()+5;)
{
myvector.erase(it);
}
for(auto it=myvector.begin();it!=myvcetor.end();it++)
cout<<*it<<endl;
//元素显示第二种方式,直接用索引来做
//for(unsigned int i=0;i<myvector.size();i++)
//cout<<' '<<myvector[i]
}