How does this method of removing an element from a stack work?
I just started taking a C++ class at my local college and the instructor gave the class an assignment in which we must create a vector and remove an element from the middle of the stack.
She provided t开发者_JAVA百科his example:
vect[3] = vect[vect.size()-1];
vect.pop_back();
Now.. I've tested it and it works I'm just unsure how it works or why it works. I'm sure someone could provide a simple explanation?
You want to delete an element from the middle of the vector, so you simply overwrite it with the last element (with index size()-1
) - since the last element thus becomes redundant, we can pop_back()
it. Finally we have the desired result - the vector size is decreased by one and the old value at vect[3]
is gone.
Note that this doesn't preserve the order of elements in the vector, but it is relatively efficient - erasing from the middle of a vector may involve a lot of memory copying since all elements after the element to be deleted need to be shifted by one to accommodate the gap (remember: a std::vector
stores its elements in continuous storage). Erasing from the end costs almost nothing.
精彩评论