What I'm trying to do is to construct a stack which contains unique elements.
And if an element is pushed to which is already in stack the element is not pushed but the existing elemetn should be moved to the top of the stack, i.e. ABCD + B > ACDB
I would like to here from you which container will be the best choice to have this functionality.
I decided to user stack adapter over list, because
The drawback of my choice is that I have to manually check for the duplicate elements.
P.S. My compiler is not so recent so please don't suggest unordered_set.
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only.
set::begin() and set::end() in C++ STL Sets are a type of associative container in which each element has to be unique because the value of the element identifies it.
top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element.
Basically you have to chose between constant time moving + long search, or constant time search + long moving.
It's hard to say which would be more time-consuming, but consider this:
I'd suggest you to store elements and their stack positions in different containers. Store elements in a way that provides fast search, store stack positions in a way that provides fast movement. Connect both with pointers (so you can know which element is on which position, and which position holds which element <-- messy phrase, I know it!), and you will perform stuff rather fast.
From your requirements, it seems to me that the structure you want could be derived from a Max Heap.
If instead of storing just the item, you store a pair (generation, item), with generation coming from a monotonically increasing counter, then the "root" of the heap is always the last seen element (and the other elements do not really matter, do they ?).
delete-max
operation)increase-key
operation)insert
operation)Given the number of elements (20), building the heap on a vector
seems a natural choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With