Learn so long of C + + library, how is not the correct insertion and removal of elements. The element that removes a specific value before, we can successfully execute the algorithm earse () and remove (). But for these algorithms, how do internal iterators work, we do not need a tube, only know for the sequential container, it will traverse the entire container, find the eligible elements and remove, for the associated container, You can remove elements of a specific value in logarithmic time, remove elements that satisfy a particular condition, and also traverse the entire container.
Now, if you want to remove and output all the elements that you want to remove.
Right, first output the element in the container, and then remove it, no matter what container, need to traverse all elements, and perform earse () for each element, then this requires us to manage the iterator, remember. The iterative failure problem that we have been emphasizing before, we are not careful, we will fall into this trap.
Sample code:
//removing elements, outputting elements before removal #include <iostream> #include <vector> #include <set> #include <
Iterator> using namespace std;
int main () {int data[]={-2,3,0,9,12,-5,-1,7};
Vector<int> Coll (data,data+sizeof (data)/sizeof (data[0));
Vector<int>::iterator POS;
For (Pos=coll.begin ();p os!=coll.end ();)
{cout<<*pos<< "";
Pos=coll.erase (POS)//Deletes the element and returns the position of the next element so the iterator does not fail and points to the next location} cout<<endl;
Set<int> coll1 (data,data+sizeof (data)/sizeof (data[0));
Set<int>::iterator pos1;
For (Pos1=coll1.begin ();p os1!=coll1.end ();)
{cout<<*pos1<< "";
Coll1.erase (pos1++);//After the element is deleted, the iterator fails, but POS1 already points to the next element position} cout<<endl;
Vector<int> s;
Vector<int>::iterator P=s.begin ();
for (int i=0;i<10;i++) {P=s.insert (p,i);//correct insertion method ++p;
Copy (S.begin (), S.end (),ostream_iterator<int> (cout, ""));
cout<<endl;
System ("pause");
return 0; }
Code Analysis:
From the above code you can see that for a sequential container, its member function earse () and insert () is returned, and the member function Earse () returns the next position of the deleted element, and insert () returns the position of the element that was just inserted. This avoids an error by processing the iterator, and must be incremented for the associative container, so that the
does not invalidate the iterator.