这里列举了vector、string、map(unordered_map)、set、deque 容器的erase方法
总结如下:
对于vector、string连续内存空间的容器,erase后返回的迭代器为删除后的下一个位置,而map、set、deque等链表类型的容器,erase后返回的迭代器为当前的位置,我们需要手动后移,两种不同类型的迭代器通用删除模板
如
vector<int> a{1,2,3,4,5,6,7};
for(vector<int>::iterator it = a.begin(); it != a.end();)
{
if(*it == 7)
{
a.erase(it); //如果删除的是7,迭代器的位置会自动后移到end()
//a=erase(it); //这种方法也行
}
else
{
it++;
}
}
unordered_set<int> st{1,2,3,4,5,6};
for(unordered_set<int>::iterator it = st.begin(); it != st.end();)
{
if(*it == 1)
{
st.erase(it++); //需要手动后移,因为删除后it的位置还是在*it=1的位置
}
else
{
it++;
}
}
//注意!!!不能将it++写在for循环中,因为这样可能会跳过一次查询,如果要将它写在for循环中,下面这种方法也行,只不过不能体现迭代器是如何后移
unordered_set<int> st{1,2,3,4,5,6};
for(unordered_set<int>::iterator it = st.begin(); it != st.end();it++)
{
if(*it == 1)
{
st.erase(it);
}
}
下面是一些测试代码,注意,如果需要输出的话,需要注意删除最后一个元素的情况,如果删除后不判断最后一个位置是否为迭代器的尾部,这样会导致段错误
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<unordered_set>
#include<vector>
#include<unistd.h>
#include<vector>
#include<unordered_map>
#include<map>
#include<string>
#include<set>
#include<deque>
#include<unordered_set>
using namespace std;
int main()
{
cout << "vector:" << endl;
vector<int> a{1,2,3,4,5,6,7};
for(vector<int>::iterator it = a.begin(); it != a.end();)
{
if(*it == 7)
{
a.erase(it);
if(it != a.end())
cout << *it << endl;
}
else
{
it++;
}
}
cout << "string:" << endl;
string s = "abcdef";
for(string::iterator it = s.begin(); it!=s.end();)
{
if(*it == 'f')
{
it = s.erase(it);
if(it != s.end())
cout << *it << endl;
}
else
{
it++;
}
}
cout << "unordered_map:" << endl;
map<int,int> mp{{1,2},{3,4},{5,6}};
for(map<int,int>::iterator it = mp.begin(); it != mp.end();)
{
if(it->first == 5)
{
mp.erase(it++);
if(it != mp.end())
cout << it->first << " " << it->second << " " << endl;
}
else
{
it++;
}
}
cout << "set:" << endl;
unordered_set<int> st{1,2,3,4,5,6};
for(unordered_set<int>::iterator it = st.begin(); it != st.end();)
{
if(*it == 1)
{
st.erase(it);
if(it != st.end())
{
cout << *it << endl; //先输出,再++
it++;
}
}
else
{
it++;
}
}
cout << endl;
cout << "deque:" << endl;
deque<int> dq{1,2,3,4,5,6};
for(deque<int>::iterator it = dq.begin(); it != dq.end();)
{
if(*it == 1)
{
dq.erase(it++);
if(it != dq.end())
cout << *it << endl;
}
else
{
it++;
}
}
cout << endl;
return 0;
}