void erase(vector &v)
{
for(vector::iterator vi=v.begin();vi!=v.end();)
{
if(*vi % 2 == 0)
{
cout << "Erasing " << *vi << endl;
vi = v.erase(vi);
} else
++vi;
}
}
正确方法2:
void erase2(vector &v)
{
for(vector::reverse_iterator ri=v.rbegin();ri!=v.rend();)
{
if(*ri % 2 == 0)
{
cout << "Erasing " << *ri << endl; v.erase((++ri).base()); //erase()函数期待的是正向iterator,故而这里要调 //用base()函数将逆向iterator转换为正向的
} else
++ri;
}
}
2.map/list 正确方法
void erase(map &m)
{
for(map::iterator mi=m.begin();mi!=m.end();)
{
if(mi->second % 2 == 0)
{
cout << "Erasing " << mi->second << endl; m.erase(mi++);
} else
++mi;
}
}