I have a struct call ‘A’, which has an attribute ‘i’, like this:
typedef struct a {
a() { i = 0;}
int i;
} A;
And I would like to maintain a stack of A in my Main class:
class Main {
public:
void save();
void doSomethingToModifyCurrentA();
void restore();
private:
A currentA;
stack<A> aStack;
}
I would like to write the function save() which save the current values of A (e.g. i) to the stack and I can go on doSomethingToModifyCurrentA() to change currentA. And then later on, I can restort A by calling restore().
My question are
- How can I allocate memory for a copy of A to the ‘stack’?
- How can I pop out the copy of A and free the memory and restore the value of ‘currentA’?
You don’t need to do anything to reserve memory on the stack. The underlying container (deque by default) manages memory for you.
The three important methods are…
The pop doesn’t read the top value – just discards it. The top method returns a reference to the current top value, so you can write…
To read or overwrite the top value.
These methods translate to the following calls in the underlying deque…
Personally, I usually just use the deque directly – though strictly, the stack is better for readability and maintainability as it better expresses the intent and prevents you from doing some things incompatible with that intent.