Correct use of STL VECOTR erase function

Source: Internet
Author: User

The Erase function either deletes the elements of LOC at the specified location, or removes all elements of the interval [start, end].

The return value is the iterator that points to the next position of the last element to be deleted

Parameters

All parameters is of member type iterator, which in vector containers is defined as a random access Iterato R type.

Position
Iterator pointing to a single element to be removed from the vector.
First, last
iterators specifying a range within the vector to be removed: [first,last]. i.e., the range includes AL L The elements between first and last, including the element pointed by first but not The one pointed by .

Return value

A random Access iterator pointing to the new location of the element that followed the last element erased by the function Call, which are the vector end if the operation erased the last element in the sequence.

Remove the element with a value of 3, supposedly it = vec.erase (it); is correct, but I experiment to find it = vec.erase (it), and vec.erase (it), can work, no crash.

#include <iostream>#include<vector>using namespacestd;intmain () {vector<int>VEC; Vec.push_back (1); Vec.push_back (2); Vec.push_back (3); Vec.push_back (4); Vec.push_back (5);  for(vector<int>::iterator it = Vec.begin (); It! = Vec.end (); it++)    {           if(*it = =3) {It=Vec.erase (IT); //Vec.erase (it);cout << *it <<"CCC"<<Endl; It--; }           Elsecout<< *it <<Endl; }       return 0;}

Note that the above cannot be written

/*
for (vector<int>::iterator it=arr.begin (); It!=arr.end (); it + +)
{
if (* it = = 8)
{
Arr.Erase(IT); After the erase , it fails, not the next element of the vector , it becomes a "wild pointer".

}
}

*/

Correct use of STL Vecotr erase function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.