By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,514 Members | 1,801 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,514 IT Pros & Developers. It's quick & easy.

erase in a vector

P: n/a

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
Nov 9 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Chad E. Dollins wrote:

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
Nov 9 '05 #2

P: n/a
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

Nov 9 '05 #3

P: n/a
> 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 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
Nov 10 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.