For vectors to use containers. Usually just a simple traversal lookup, other operations have been performed, which is not, today, slightly careless.
The action of the erase method is to delete the node at this point, and then point to the next node that is deleted:
As to Data 1 6 6 4 7;
#include <iostream> #include <vector> #include <algorithm>using namespace Std;int main () { vector <int> Vec; Vec.push_back (1); Vec.push_back (6); Vec.push_back (6); Vec.push_back (4); Vec.push_back (7); Vector<int>::iterator arr; Vec.erase (Remove (Vec.begin (), Vec.end (), 6), Vec.end ()); for (arr = Vec.begin (); Arr! = Vec.end (); arr++) { if (6 = = *arr) { vec.erase (arr); arr--; } } cout << "The size of vector is:" << vec.size () << Endl; for (arr = Vec.begin (); Arr! = Vec.end (); arr++) { cout << *arr << " "; } cout << Endl; return 0;}
The results of the
above actions are as follows:
Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvegptmtk5/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/southeast ">
One 6 was not successfully deleted because the iterator was arr++after each loop, and after the node was successfully deleted, a bit was moved. In fact, when the deletion is done, it moves back two bits, so when it is deleted:
for (arr = Vec.begin (); Arr! = Vec.end (); arr++) { if (6 = = *arr) { vec.erase (arr); arr--; } }
with the
arr-- operation, you can offset your own active back-shift when deleting. Thus successfully:
Of course, erase has another way of removing all the elements between two nodes. This relies on the remove operation to move all nodes that are equal to the deleted value to the end of the container. To delete;
The gaze of the above for loop is removed by the vec.erase (remove (Vec.begin (), Vec.end (), 6), Vec.end ()) on the previous line; Gaze cancellation can be achieved;
#include <iostream> #include <vector> #include <algorithm>using namespace Std;int main () { vector <int> Vec; Vec.push_back (1); Vec.push_back (6); Vec.push_back (6); Vec.push_back (4); Vec.push_back (7); Vector<int>::iterator arr; Vec.erase (Remove (Vec.begin (), Vec.end (), 6), Vec.end ()); /*for (arr = Vec.begin (); Arr! = Vec.end (); arr++ ) { if (6 = = *arr) { vec.erase (arr); arr--; } } * /cout << "The size of vector is:" << vec.size () << Endl; for (arr = Vec.begin (); Arr! = Vec.end (); arr++) { cout << *arr << " "; } cout << Endl; return 0;}
O (∩_∩) o
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Vector Delete, erase and remove no wonder--"STL"