views:

110

answers:

4

Sorry I can't provide code bc I don't have it.

My coworker (who has been with the company for a long time but doesn't appear to know what he's doing) claims that he has to do some weird stuff to remove elements from a vector. He moves all the elements down a position (starting at the element that he wants to remove) then he'll remove the last element in the vector. This sounds OK but very inefficient. The standard library's std::vector::erase() should be able to handle this fine.

He does this because he claims that calling erase on element 0 gives random exceptions.

My question is what could cause this? I am pretty sure that this is a thread-safety problem, but is there anything else that could cause it?

Please let me know...I'm new to C++.

Again, sorry for not being able to provide code.

Thanks, Jbu

+4  A: 

... calling erase on element 0 gives random exceptions.

No it doesn't.

That's all the answer you can expect without a lot more info about what he's actually doing.

meagar
+2  A: 

The only place where calling erase on element zero would be throwing exceptions would be cases where undefined behavior would have already been invoked. Most commonly, trying to erase element zero from an empty vector.

This sounds OK but very inefficient.

Not really -- that's what erase is doing anyway. But it makes no sense to reimplement things the standard library already does for you.

Billy ONeal
Since (the standard version of) `std::vector::erase` requires using an iterator, it's also possible that an operation was performed on the vector that invalidated existing iterators.
jamesdlin
+1  A: 

Without code it's difficult to say. If vector::size() > 0, then erasing element 0 is completely valid. It could be he's using an iterator to erase the 0th element, and the iterator has been invalidated somehow.

Charles Salvia
A: 

Based on your description of coworker's logic, I'd say your appraisal is accurate. 'Random exceptions' = 'undiagnosed bug due to misuse of the vector container'.

That said, the question is a bit pointless - if you can't provide the source, how can you get a definitive answer on what's wrong or otherwise?

Steve Townsend