在我们开发过程中常常会用到STD中的一些容器,容器的使用无非就是增删修查等操作,今天要说的是关于STD中常用容器vector/list/map遍历条件删除元素的问题。
我们知道直接遍历容器的所有元素很简单,直接for循环就阔以,但是如果是遍历容器并且删除满足条件的元素的时候就要注意了,因为如果按照常规的遍历直接删除的方式会出错(此处可以自己写个简单的测试用例验证一下),那么正确的遍历条件删除的操作是怎样的呢,下面就列出常用的三种容器vector/list/map的遍历条件删除的方法,当然这只是正确方法中的一种,但是是比较见到的,其他的方式自行验证可以即可。
1.std::vector的遍历条件删除
std::vector<int> intvector;
intvecotr.push_back(1);
intvecotr.push_back(2);
for(auto itr = intvector.begin();itr!=intvector.end();)
{
if(1 == (*itr))
{
intvecotr.erase(itr);
itr = intvector.begin(); //这行是关键
}
else
{
itr++;
}
}
2.std::list的遍历条件删除
std::list<int> intlist;
intlist.push_back(1);
intlist.push_back(2);
for(auto itr = intlist.begin();itr!=intlist.end();)
{
if(1 == (*itr))
{
intlist.erase(itr++);//注意这儿一定要++
}
else
{
itr++;
}
}
3.std::map的遍历条件删除
std::map<int,int> intmap;
intmap.insert({1,1});
intmap.insert({2,2});
for(auto itr = intmap.begin();itr!=intmap.end();)
{
if(1 == itr.frist)
{
intmap.erase(itr++);//注意这儿一定要++
}
else
{
itr++;
}
}
综上可以看出,list和map的遍历条件删除逻辑是相同的,但是vector的就有所差异,这一点需要注意,日后使用的过程中需要多留心。