deleting last element from vector

Aug 1, 2010 at 10:07pm
I am trying to delete 14 from vector which is inserted twice. My code deletes first 14 but not last 14. any idea why?

int main()
{
vector<int> vect;
vector<int>::iterator itr=vect.begin();

for (int i=1; i<=10; i++)
{
vect.push_back(i+10);
}
vect.push_back(14);

for (itr=vect.begin();itr<vect.end(); itr++)
{
if (*itr==14)
itr=vect.erase(itr); // It deletes first 14 but not last 14

cout<<*itr<<" ";
}
return 0;
Thanks in advance!
VJ
Aug 1, 2010 at 10:14pm
Yes it does.
You are just doing something uncouth by accessing an erased item.

[edit] Reconsider your loops. Hope this helps.
Last edited on Aug 1, 2010 at 10:15pm
Aug 1, 2010 at 10:23pm
If you use g++, you should define _GLIBCXX_DEBUG in debug mode. Then you would have received an error message such as this:

error: attempt to dereference a past-the-end iterator.


Besides that you're trying to dereference itr even though it could equal end() after the previous line, you're also skipping the element right after each 14 - two consecutive 14s can't be found. This fixes both problems (although not advancing the iterator until the next iteration would be better instead of going back):

1
2
if (*itr==14)itr=--vect.erase(itr);
else cout << *itr << " ";


Oh, and you should use operator!= when doing the check for end() - it will work with all iterators, which can't be said for operator<.
Last edited on Aug 1, 2010 at 10:32pm
Aug 1, 2010 at 10:27pm
Thanks for reply. So it means, at one loop, we can delete only one element (except some range). We can not delete two element in one loop? if yes, then can you please explain why?
Aug 1, 2010 at 11:04pm
Thanks for reply. So it means, at one loop, we can delete only one element (except some range).

No, why would you think that?
Aug 1, 2010 at 11:11pm
sorry, I posted before seeing your comment. I got. Thanks for help.
Topic archived. No new replies allowed.