Map/set iterator not incrementable set/map use erase precautions!

Source: Internet
Author: User

Recently wrote a few questions, using the STL set this container, when I want to traverse the set to complete a specific erase operation, but there is Map/set iterator not incrementable exception report.


That's what most people write:

Set<int> S;
for (Set<int>::iterator it = S.begin (); It! = S.end (); it++)
	if (a condition) erase (IT);

The exception report with Map/set iterator not incrementable was discovered after running, because this element in the collection s does not exist after performing the erase (it) operation, so it The point of course is not still the original address.


So this time we want to make it point to the last element of the deleted element, you can do this:


Set<int> S;
for (Set<int>::iterator it = S.begin (); It! = S.end ();)
	if (a condition) it = erase (it);       C++11 Erase returns a iterator and points to the next element of the deleted element
	else it++;            Because erase is not used, you can still it++

I hope we can solve the 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.