简体   繁体   中英

Stack with maximum size that overwrites C++

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 .

I would use a std::deque and delete an element when the size gets over the limit. Of course a list would work just as well, as you have observed.

There's not a standard container to do this.

An std::deque or an std::list both work. You can use them as a stack by using push_back / pop_back and expire old elements with pop_front

如果您愿意在STL之外工作,boost会提供一个名为circular_buffer的容器,该容器非常适合您的需求: http : //www.boost.org/doc/libs/1_49_0/libs/circular_buffer/doc/circular_buffer.html #briefexample

I don't know if you want to do this but it seems to me like you want a circular buffer. It isn't STL afaik but it will do exactly what you want. Have a look at http://en.wikipedia.org/wiki/Circular_buffer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM