C++20前,vector可以通过成员函数erase删除迭代器指定的元素,并返回被删除的下一个元素:
iterator erase( iterator pos );
iterator erase( iterator first, iterator last );
1.删除单个元素
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void pData(auto& data)
{
for(auto& i : data)
{
cout<<i<<" ";
}
cout<<endl;
cout<<"size:"<<data.size()<<" capacity:"<<data.capacity()<<endl;
}
int main()
{
vector<int> data{ 1, 2, 3, 4, 5, 6, 7, 8};
pData(data);
for(auto it=data.begin(); it!=data.end();)
{
if(*it % 2 == 0)
{
it = data.erase(it);
}
else
{
it++;
}
}
pData(data);
return 0;
}
运行程序输出: