Error: Container duration eraser causes invalid iterator

Source: Internet
Author: User

Annotation: there is still a problem with the delete method 1. You should save the elements to be deleted and delete them one by one.
By debehe 2008.01.22

This mistake was made again. You can't help but remember :)

Each element of the container is a struct, and the elements in the struct are created on the stack. to delete an element, you must first release the memory allocated in the struct. Therefore:
When iterator is used to traverse a container in a for loop, while eraser (iterator) is traversed, it seems that there is no problem. In fact, there is a big error.

Cause of error:
Because after eraser (iterator) is executed, an iterator is returned, that is, the next element to be deleted, and the iterator used by the for loop has changed, however, I continue to ++ iterator. The ++ here is no longer as I imagined "subscript index plus 1 "!! An error occurs.

Correct methods to traverse and delete elements:
1. You can use reverse_iterator, rbegin, and rend to delete from the back to the front,
2. Do not use erasor, or clearall, or... remember that the iterator has changed. Nothing else is a problem.

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.