Erase usage and return value of STL container Set,map,vector detailed parsing _c language

Source: Internet
Author: User

Summarize my experience and lessons in the work.

You can use the list, set, or map traversal to remove certain elements:

Correct use of Method 1

Copy Code code as follows:

std::list< int> list;
std::list< Int>::iterator itlist;
for (itlist = List.begin (); itlist!= list.end ();)
{
if (Willdelete (*itlist))
{
Itlist = List.erase (itlist);
}
Else
itlist++;
}

correct use of Method 2
Copy Code code as follows:

std::list< int> list;
std::list< Int>::iterator itlist;
for (itlist = List.begin (); itlist!= list.end ();)
{
if (Willdelete (*itlist))
{
List.erase (itlist++);
}
Else
itlist++;
}

Correct use of Method 3
Copy Code code as follows:

std::list< int> list;
std::list< Int>::iterator it, next;
for (it = List.begin (), next = it, next + +; it!= list.end (); it = Next, ++next)
{
if (Willdelete (*it))
{
List.erase (IT);
}
}

Note: The method three is more ingenious, but need to pay attention to method three is before use to determine whether the container is empty, otherwise the iterator will be problematic.

I test that set.erase does not return the iterator, and the list returns.
Vector delete operation

Copy Code code as follows:

Std::vector <pack_print>::iterator It;
For (It=printitems.begin (); It!=printitems.end ();)
{
I mean, how do we judge Printitems Printitems pack_print.bh =0

if (it.bh ==0)//is that so?
{//delete
It=printitems.erase (It);
}
Else
{//Do not delete
++it;
}
}


Copy Code code as follows:

Std::vector <PACK_PRINT> Printitems;
int i = 0;
while (I < printitems.size ())
{

if (printitems[i].bh = 0)//Here for example I want to printitems when pack_print.bh =0 delete how to write Yo. In addition, is it wrong to delete this?
{//delete
Printitems.erase (Printitems.begin () + i);
}
Else
{//Do not delete
++i;
}
}

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.