I work on a c++ project in my course and I can not do Vector erase

I write our records in a text file and read them in

a vector and I should erase a specific data in them

and write this vector to text file this new vector list.

However when I try to erase last object in vector, some error occur...

after adding data into vector memberType ...

when status is 0 I want to erase this object form vector...

1
2
3
4
5
6
7
8
9
10
11
12
	for(it = memberType.begin();it!=memberType.end();it++)
	{
		cout<<(*it).getMember().status<<" ";
		if((*it).getMember().status)
		{

		}
		else 
		{
			memberType.erase(it);			
		}
	}

Error type


Unhandled exception at 0x0032329f in cmpe210p1.exe: 0xC0000005: Access violation reading location 0x00596000.
Last edited on
Do this instead

vector.erase(vector.begin() + vector_access_instance);

where vector in your case is memberType.
While you erase a iterator in vector,the iterator become a wild pointer in Visual Studio.If you still use it,the compiler will show the access violation reading error.
For another compiler, after removing the element, the vector erase make the iterator return next element.
if you just want to solve it,you can choose ultifinitus's solution.

Or you can use the remove_if.
Last edited on
1
2
3
4
5
6
if(/* */){
  //...
  it++;
}
else
  it = memberType.erase(it);
I had this issue a few weeks ago, it worked with xcode, but not windows. I solved by using a while loop instead of for loop, and putting a Post-increment operator with the iterator being sent as an argument. ( and of course incrementing it in the if part in case if is true )
Topic archived. No new replies allowed.