A problem with STL list

Hello there,

so I've created a code with STL list which works just fine
Here is the code

// here is main.h file
#include <iostream>
#include <iomanip>
#include <list>

using namespace std;

class Person
{

public:

//Person();
//~Person();

int getPosition()
{
return position;
};

void setPosition(int n)
{
position = n;
};

private:
int position;
};

//here is main.cpp file

#include "main.h"
int main ()
{
list <Person> circ;
Person player;

int i;
for (i = 0; i < 4; i++) // insert players into the circle
{
player.setPosition(i);
circ.push_back(player);
}

int remove = 0;

list<Person>::iterator j = circ.begin();

while (j!= circ.end())
{
if (j->getPosition() == remove) // if the player has the target
// position
{
j = circ.erase(j); // eliminate player from the circle
}
j++;
}

for (j = circ.begin(); j != circ.end(); j++)
cout << j->getPosition();
cout << endl;
}

My problem is when I set the variable "remove" to be = 3 which is I think the end of the list, the program crashes directly, but when I assign it from 0 - 2 it works just fine. Can anyone help me fixing this, please?
Don't see any problems. Also it works just fine for me with remove==3.

EDIT: doh, yeah I see it now. Strange how I missed it when someone had the exact same problem earlier today.

Also strange how it doesn't crash for me....
Last edited on
If you "remove" the last element with that code, j is set to circ.end(), then you increment it causing undefined behavior.

1
2
3
4
5
6
7
while (j!= circ.end())
{
    if (j->getPosition() == remove)
        j = circ.erase(j); // eliminate player from the circle
    else
        ++j;
}
Please enclose your source code in code tags next time
But it isnt crashing for me
Last edited on
OH I spent 3 hours to fix it! I didn't know how small mistake it is!

THANK YOU cire so much
Topic archived. No new replies allowed.