erase in a vector

  • Thread starter Chad E. Dollins
  • Start date
C

Chad E. Dollins

I would like to know how to remove an element from a vector. The following
give a segmentation fault perhaps someone can give me a proper explanation
why:

vector<T> * myCon;
//...some code that adds T to the container
vector<T>::iterator p1;
for(p1 = myCon->begin();p1 != myCon->end();++p1)
myCon->erase(*p1);
This may have syntax errors but the orignal code does not.
when erase is called on a seg fault happens. T has a default destructor.

Thanks,
--Chad
 
J

John Harrison

Chad said:
I would like to know how to remove an element from a vector. The
following give a segmentation fault perhaps someone can give me a proper
explanation why:

vector<T> * myCon;
//...some code that adds T to the container
vector<T>::iterator p1;
for(p1 = myCon->begin();p1 != myCon->end();++p1)
myCon->erase(*p1);
This may have syntax errors but the orignal code does not.
when erase is called on a seg fault happens. T has a default destructor.

Think about what happens to your code when you erase the last element in
your vector.

p1 is pointing to the last element (the one before end())
you erase that element (p1 is now pointing at end())
you advance p1 (p1 is now pointing past end())
you test (p1 == end()) fails and you go on happily deleteing into infinity.

Here's how to do it

myCon->clear();

Alternatively if you really want a loop then

vector<T>::iterator p1 = myCon->begin();
while (p1 != myCon->end())
p1 = myCon->erase(p1);

john
 
G

Gregory

The erase() is OK, but right after the erase() the iterator
pointing to the erased element is invalidated, so you can't use ++
operator on it. However erase() itself returns an iterator of the
element next to the erased one. So you need to modify your code this
way:

vector<T>::iterator p1;
for(p1 = myCon->begin();p1 != myCon->end();)
{
p1 = myCon->erase(*p1);
}

Hope this helps.

Gregory
 
M

Marcin Kalicinski

vector said:
//...some code that adds T to the container
vector<T>::iterator p1;
for(p1 = myCon->begin();p1 != myCon->end();++p1)
myCon->erase(*p1);

This is a very obfuscated and wrong way to clear a vector. Why not just call
myCon->clear()?

Aside from that, your error is that erase invalidates all iterators pointing
to the element being erased, in your case this is p1, so you cannot use it
anymore. Use return value of erase instead.

cheers,
Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,268
Latest member
AshliMacin

Latest Threads

Top