Problem with list / struct

Hello,

i got a problem with my c++ code where i using struct to make variables to
my list. The program is to list users thats added (user1, user2), i can add user3 but! When i try to delete one of the users the program crash and some times it dosen't. The error i get dosen't help me at all so im asking you guys here for help :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <string>
#include <list>

using namespace std;

struct userdata
{
	string username;
	string password;
};

int main() 
{
	int val;
	string anv;
	userdata user1;
	user1.username = "hej";
	user1.password = "hej";
	
	userdata user2;
	user2.username = "lol";
	user2.password = "lol";
	list<userdata> datalist;
	
	datalist.push_back(user1);
	datalist.push_back(user2);
	userdata user3;
	bool apa = 0;

	while(apa == 0)
	
	{


	cout << "1: Add user" << endl;
	cout << "2: Delete user " << endl;
	cout << "3: List all users" << endl;
	cout << "4: Exit" << endl;
	cin >> val;
	switch (val) 
	{
	case 1: 
				
			cout << "Skriv in ditt anvadarnamn: ";
			cin >> user3.username;
			cout << endl;
			cout << "Valj ett losenord: ";
			cin >> user3.password;
			cout <<"inlaggd"<<endl;
			datalist.push_back(user3);
			break;

	case 2:
				cout << "Vilken anvandare vill du ta bort?" << endl;
				cin >> anv;
			for(list<userdata>::iterator it = datalist.begin(); it != datalist.end(); it++)
			{
			if((*it).username == anv)
				{
					it = datalist.erase(it);
				}
			}
			
	break;
	case 3: 

	for(list<userdata>::iterator it = datalist.begin(); it != datalist.end(); it++)
	{
		cout << "Anvandar namn: " << (*it).username << " med losenord: " << (*it).password << endl;
	}

		break;

	case 4: 
		apa = 1;
		break;

	default: 
		cout << "Valj numer 1,2,3,4!" << endl;
		break;
	}
	}
	
	system("pause");
	return 0;
}
I ran it and used it and it runs perfectly, i ended up deleting all users, adding new users, listed all of the users and exit without any crashes. What exactly is the matter?
Also please try commenting the code so people like me dont have too scan through the code looking for whats going on. Because i dont understand the language that pops up when not in the main menu, so i had to search for what it was doing :) just a suggestion
closed account (DSLq5Di1)
erase() returns an iterator to the next element, your for loop will attempt to increment that iterator again, before evaluating the end condition.

1
2
3
4
5
6
7
8
9
10
11
for(list<userdata>::iterator it = datalist.begin(); it != datalist.end(); it++ /* remove */)
{
	if((*it).username == anv)
	{
		it = datalist.erase(it); // the iterator is incremented here
	}
	else
	{
		it++; // only increment if there was no erase operation
	}
}
Topic archived. No new replies allowed.