Deleting from vector with iterator (99% sure this is the way to go)

Started by
21 comments, last by dimitri.adamou 11 years, 9 months ago

Wierd no one thought to check if the vector wasnt empty before running that delete state...

a simple

if(!vector.empty())
{
do delete code stuff
}

It sounds like its trying to access a element that doesnt exist, and it never hurts ( at least I dont think it does ) to check if a container is empty before doing stuff.


But if the vector is empty the for loop wont run at all if i understand it right. And the code works now(same that i posted), i guess i had sloppy code somewhere else.
Advertisement
Still a good idea to have that check, even if you are certain it wont call an empty vector... if you are concerned that it merely hides bad code you could add a error conditon so it notifies / logs the fact a call to the vector was made even though its empty.

if vector is not empty - do stuff - else - report attempt to access empty vector.

At least you will know that you were somehow accessing a empty vector, I use that a lot and it saves me quiet a lot of headaches.
I find a lot of time when programming I think something should do xyz, and never abc but due to silly faults what I get is abc, and as I have convinced myself the result cant be abc I cant work out why the code isnt working... if I set up my code to report back ( usually a text msg on screen, or a pass a msg to a vector I use to store msgs and display them in a console like function ), I can see what it is actually doing, rather than what I think it should be doing.
iterators will only point to the end if its empty but yeah the habbit of checking is good

This topic is closed to new replies.

Advertisement