vector循环删除的时候,erase(it)会返回下一个迭代器的地址,保险的做法是赋值给it 即 it= erase(it)
这是vector的内部机制所造成的,所以对vector进行erase的时候特别注意迭代器是否会失效!
map则可以直接erase(it++);
vector和map都不能将it++写在for循环中,而在循环体内erase(it)!
void main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(4);
v.push_back(3);
v.push_back(6);
v.push_back(5);
cout << v.size() <<endl;
vector<int>::iterator it;
for(it = v.begin();it != v.end();)
{
if(*it % 2 == 0)
//v.erase(it++);
//it = v.erase(it);
v.erase(it);
else
it++;
}
cout << v.size() <<endl;
for(it = v.begin();it != v.end();it++)
{
cout << *it << " ";
}
// map的完美删除
map<int, int> m;
m[1] = 1;
m[2] = 2;
m[3] = 4;
m[4] = 3;
m[5] = 5;
m[6] = 6;
cout <<"m size = "<<m.size() <<endl;
map<int, int>::iterator it1;
for(it1 = m.begin(); it1!=m.end();)
{
if(it1->second % 2 == 0)
m.erase(it1++);
else
it1++;
}
cout <<"2的整数倍删除后应该剩下i3";
cout <<"m size = "<<m.size() <<endl;
}