Copy Code code as follows:
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
using namespace Std;
void Remove1 (vector<int> &vec, int num)
{
Vector<int>::iterator ITER;
For (Iter=vec.begin (); Iter!=vec.end (); ++iter)
{
if (*iter = num)
{
Vec.erase (ITER);
}
}
}
void Remove2 (list<int> &lst, int num)
{
List<int>::iterator ITER;
For (Iter=lst.begin (); Iter!=lst.end (); ++iter)
{
if (*iter = num)
{
Lst.erase (ITER);
}
}
}
int main (void)
{
int arr[] = {1, 3, 5, 5, 7, 9};
int num = sizeof (arr)/sizeof (arr[0));
Vector<int> Vec (arr, arr+num);
list<int> LST (arr, arr+num);
Remove1 (VEC, 5);
Copy (Vec.begin (), Vec.end (), ostream_iterator<int> (cout, ""));
Remove2 (LST, 5);
Copy (Lst.begin (), Lst.end (), ostream_iterator<int> (cout, ""));
return 0;
}
Look at the above Remove1, Remove2 These two functions are to delete all the elements in the container is num, at first glance seems to be no problem, in fact, is wrong.
They have no problems compiling, but there are problems with running:
First comment Remove2 These two lines, compile run, get the result is: 1 3 5 7 9
Obviously the result was wrong, because there was another 5 not erased. The reason for this is that ITER vec.erase after the ++iter, and executes the next for loop, skipping over elements adjacent to the deleted element.
Take a look at the Remove2, comment out the Remove1, and delete the Remove2 annotation.
Run error, vs2005 Expression:list iterator not incrementable, description list iterator ++iter problem.
List is a two-way list, after erase (ITER), ITER expires, printf ("0x%x", ITER); The result is 0, and only the erase return value can point to the next element.
the correct usage of REMOVE1 is: vec.erase (Remove (Vec.begin (), Vec.end (), 5), Vec.end ());
the correct usage of Remove2 is:lst.remove (5);
Here's another way to do it correctly:
Copy Code code as follows:
void Remove1 (std::vector<int> &vec, int num)
{
Std::vector<int>::iterator iter = Vec.begin ();
while (ITER!= vec.end ())
{
if (*iter = num)
{
iter = Vec.erase (ITER);
}
Else
{
++iter;
}
}
}
Delete a class of elements, such as an even number
void Remove3 (std::set<int>& sets)
{
Std::set<int>::iterator iter = Sets.begin ();
while (ITER!= sets.end ())
{
if (0 = (*iter)%2)
{
Note that this cannot be written as ++iter, which explains why.
Sets.erase (iter++);
}
Else
{
++iter;
}
}
}
void Remove4 (Std::map<int, int>& maps)
{
Std::map<int, Int>::iterator iter = Maps.begin ();
while (ITER!= maps.end ())
{
if (0 = (iter->first)%2)
{
Maps.erase (iter++);
}
Else
{
++iter;
}
}
}
Set and map are implemented by the red and black trees, and the iterator fails when erase, which means we have to keep a copy of the iterator before it expires, so that we can continue to traverse the next element. i++ and ++i Obviously the former meets our requirements, so in erase it's iter++.