If I were making something like an undo stack, and I wanted to only support 30 undo operations, it would be nice to have a stack that had a maximum depth of 30.
You obviously wouldn’t want the stack to restrict additions at this point, you would just want it to discard the bottom-most element when a 31st was added.
I’m aware I can mimic this kind of functionality with a list, but I was wondering if there’s a way to make it happen with STL or if there are other pre-implemented options for this?
I would use a circularly-linked list (or just a buffer that you use circularly) with 30 nodes (or elements). You would start of the top and bottom pointers at the same node, and advance the top whenever you added an element and regress it when you remove one. if you add so many elements that you reach the bottom (you have gone all the way around the loop) then you advance the top and the bottom pointer so that they don’t cross each other, and overwrite the one that was under the bottom pointer (where the top pointer now points).
Another way to do it is to allocate an array (or wrap around a
vector) instead of dynamically allocating memory, and modulusing your indices by 30 when you want to advance an index.Either way, you never have to allocate or deallocate memory except at the beginning and you can handle overflowing really well. You can read the specifics at the Wikipedia page about circular buffers.