Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this 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?

like image 329
Oskenso Kashi Avatar asked Jan 28 '26 16:01

Oskenso Kashi


1 Answers

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.

like image 108
Alexander Gessler Avatar answered Jan 30 '26 06:01

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!