C++ vector 删除符合条件的元素
C++ vector中实际删除元素使用的是容器vecrot中std::vector::erase()方法。
C++ 中std::remove()并不删除元素,因为容器的size()没有变化,只是元素的替换。
1.std::vector::erase()
函数原型:iterator erase (iterator position); //删除指定元素
iterator erase (iterator first, iterator last); //删除指定范围内的元素
返回值:指向删除元素(或范围)的下一个元素。(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)
2.样例
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
vector<int> veci;
vector<int>::iterator it;
int i;
for (i = 0; i < 30;i++)
{
veci.push_back(i);
}
for (it = veci.begin(); it != veci.end(); )
{
if (*it%3==0)
{
it = veci.erase(it);
}
else
{
++it;
}
}
for (int i = 0; i < veci.size();i++)
{
cout << veci.at(i) << " ";
}
cout << endl;
cout << "========将vector值传递给其他参数,同时判断是否满足删除要求========" << endl;
vector<int>::iterator itc = veci.begin();
vector<int> vecTemp;
for (int i = 0; i < veci.size(),itc!=veci.end();i++)
{
vecTemp.push_back(veci.at(i));
if (*itc % 2 == 0)
{
itc = veci.erase(itc);
i--;
}
else
{
++itc;
}
}
for (int i = 0; i < veci.size(); i++)
{
cout << veci.at(i) << " ";
}
cout << endl;
for (int i = 0; i < vecTemp.size(); i++)
{
cout << vecTemp.at(i) << " ";
}
return 0;
}
参考:https://www.cnblogs.com/xudong-bupt/p/3522457.html