Erase function call problem in STL container

Source: Internet
Author: User

Self-sensing, the erase function returns an iterator that points to the next position of the deleted element, not very reasonable.

Do not say anything, directly on the code:

int findnum = 2;
int array[] = {1, 2, 2, 4, 5, 6};
Vector<int> Ivec (array, array + sizeof (array)/sizeof (*array));
for (Vector<int>::iterator iter = Ivec.begin (); I! = Ivec.end (), iter++)
{
if (*iter = = FindNum)
{
iter = Ivec.erase (ITER);
Continue
}
Else
{ }
}

This code, seemingly no problem, in fact, ITER after the re-assignment, and then again + +, will skip an element, in this case, the third element 2 will be skipped.

Change the conditions, the element to be looked up from 2 to 6 what happens, the dead loop or direct collapse, in which the reason is self-evident, continue after the ITER is equal to end (), and then again + +, will point to end () position, this position is illegal.

The first step, before continue, plus iter--

Just half, try to change the search element to 1, what will happen, iter--will collapse.

Therefore, there is a need to add a judgment:

if (iter! = Ivec.begin ()) iter--;

This problem can also be used to move the FOR loop increment statement iter++ from the head to the loop body and the + + operation in else.

Erase function call problem in STL container

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.