Vector::erase (): Deletes an element in a specified position or a range of elements from a specified container
There are two overloaded forms of the Vector::erase () method
As follows:
Iterator Erase (iterator _where);
Iterator Erase (iterator _first, iterator _last);
If you are deleting an element at a specified location:
The return value is an iterator that points to the next element of the deletion element;
If you are deleting an element in a range: The return value also represents an iterator, pointing to the next element of the last deletion element;
Look at the program below to delete all elements in the array with a value of 6:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> array;
Array.push_back (1);
Array.push_back (6);
Array.push_back (3);
Array.push_back (6);
Array.push_back (6);
Array.push_back (2);
Vector<int>::iterator Itor;
Vector<int>::iterator Itor2;
For (Itor=array.begin (); Itor!=array.end ();)
{
if (6==*itor)
{
itor2=itor;
Itor=array.erase (Itor2);
}
itor++;
}
Itor=array.begin ();
For (Itor=array.begin (); Itor!=array.end ();)
{
cout<< (*itor++);
}
GetChar ();
return 0;
}
Run results output 1362, which shows that one of the 6 has not been deleted, which is an iterator problem.
The reason is that after erase, Itor has already pointed to the next element and should not be itor++, otherwise it skips the next element, skipping the second 6 in two consecutive 6 o'clock.
In addition, when Itor2=itor, two itor are the same, it does not make sense. Can be modified as follows:
Vector<int>::iterator Itor;
Vector<int>::iterator Itor2;
For (Itor=array.begin (); Itor!=array.end ();)
{
if (6==*itor)
{
//itor2=itor;
Itor=array.erase (itor);
}
else
{
itor++;
}
}
Or:
Vector<int>::iterator Itor;
For (Itor=array.begin (); Itor!=array.end (); itor++)
{
if (6==*itor)
{
itor=array.erase (itor);
itor--
}
}
You can also use the Remove method:
Array.earse (Remove (Array.begin (), Array.end (), 6), Array.end ());