Use the erase () method in STL to traverse and delete elements.

Source: Internet
Author: User
Containers in STL are divided into two types by storage method: containers stored in arrays (such as vector and deque), and containers stored in discontinuous nodes (such: list, set, map ). When using the erase method to delete elements, pay attention to some issues.

When using list, set, or map traversal to delete some elements, you can use the following method:

correct method 1

STD: List list;
STD: List :: iterator itlist;
for (itlist = List. begin (); itlist! = List. end ();)
{< br> If (willdelete (* itlist)
{< br> itlist = List. erase (itlist);
}< br> else
itlist ++;
}< br>

when using vector and deque to traverse and delete elements, you can also use the erase return value to obtain the location of the next element:

correct usage

STD: vector VEC;
STD: vector :: iterator itvec;
for (itvec = Vec. begin (); itvec! = Vec. end ();)
{< br> If (willdelete (* itvec)
{< br> itvec = Vec. erase (itvec);
}< br> else
itlist ++;
}

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.