C + + list in the time to delete the node method, with the source code

Source: Internet
Author: User
Tags sprintf

Today in the development process encountered problems, want to traverse a list of nodes, meet certain conditions to delete the node, but because the use of the iterator will appear errors, and finally find a solution, and wrote a test program, hehe:



ListTest.cpp:Defines the entry point for the console application.

#include "stdafx.h" #include <iostream> #include <list> #include <algorithm> using namespace std;
	struct St_user {int id;
Char name[255];

};

	int _tmain (int argc, _tchar* argv[]) {St_user a1,a2,a3;
	A1.id = 1;
	sprintf (A1.name, "%s", "xxxxxxxxx");
	A2.id = 2;
	sprintf (A2.name, "%s", "FFF");
	A3.id = 3;

	sprintf (A3.name, "%s", "bbbb");

	List<st_user*> List1;
	List1.push_back (&AMP;A1);
	List1.push_back (&AMP;A2);


	List1.push_back (&AMP;A3);


	printf ("------------------------------\ n"); for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter) {printf ("%s \", *iter)->nam
	e);


	printf ("------------------------------\ n");
	for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end ();)
		{if ((*t)->id = = 2) {iter = List1.erase (t);

	else ++iter;


	printf ("------------------------------\ n"); for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter) {printf ("%s \ n", (*iter)->name);


	printf ("------------------------------\ n");


	System ("pause");
return 0;
 }



Run Result:



--------------------------------------

@2015-7-20 10:06:01 fixed the errors mentioned by netizens, haha, this error is too low, please forgive

The original error code:

	for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter)
	{
		if ((*t)->id = = 2) 
  {
			list1.erase (t);
		}
	



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.