Erase-induced iterator Failure Analysis (C++11)

Source: Internet
Author: User

Erase in the loop:

(1) For an associative container, nothing is returned after erase, and subsequent iterators cannot be down, that is, you cannot perform ++it or it--operations. What needs to be done is to it++ the iterator when it is deleted, so that it is OK to go down.

(2) For a sequence container, the next iterator is returned after erase, but causes all subsequent iterators to fail, and if you want the loop to continue, save the return value of the iterator and start the iteration here.

Regardless of the container, the regular three-segment for () is no longer applicable.

In c++11, Erase returns the next iterator, but the previous version returns void. Erase was poorly designed, making it easier for the person to make a mistake. Defective c++!.

void Erase( iterator pos); (Until c++11)
Iterator Erase( const_iterator pos); (Since c++11)

void Erase( iterator first, iterator last); (Until c++11)
Iterator Erase( const_iterator First, const_iterator last); (Since c++11)

However, many compilers currently do not support c++11, or are only partially supported. So it's best to use the surest way to write it++ out of the loop.

(1) Associative container (take map for example)

For (It=map.begin (); It! = Map.end (); )

{

if (CanDelete (IT))map.erase (it + +); In c++11, you can write only map.erase (it), but first confirm that your compiler supports C++11, such as g++ 4.7.3.

else ++it;

}

(2) Sequence container (take vector as an example)

for (it = Vector.begin (); It! = Vector.end ();)

{

if (CanDelete (it)) it = vector.erase (it); To keep the returned value in it, it will be in an invalid state, and then the ++it will be meaningless. C++11 Associative containers can also be written like this

else + + it;

}

Erase-induced iterator Failure Analysis (C++11)

Related Article

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.