C + + prevents--map/set such as associative containers such as iterator invalidation in STL--vector/list/deque-How to prevent iterators from being invalidated-that is, the use of erase ()

Source: Internet
Author: User

Sequential containers::(vectors and lists and deque)

The erase iterator not only invalidates all iterators that point to the deleted element, but also invalidates all iterators after the deleted element, so erase (iter++) cannot be used, but the return value of erase is the next valid iterator, so the correct method is:: For (iter = C.begin (); ITER! = C.end ();)

iter = C.erase (ITER);

Associative containers::(map and set are more commonly used) The erase iterator is only invalidated by the iterator of the deleted element, but the return value is void, so the iterator is removed in the erase (iter++) manner, with the correct method:

for (iter = C.begin (); ITER! = C.end ();)

C.erase (iter++);

Tips:

In fact, for the list of two ways to work properly

C + + prevents--map/set such as associative containers such as iterator invalidation in STL--vector/list/deque-How to prevent iterators from being invalidated-that is, the use of erase ()

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.