views:

97

answers:

4

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'?
+3  A: 

In the C++ STL library there is a stack implementation you can use and there's the push and pop methods.

push is used to add an item to the stack and pop is used to pop one off the stack.

Have a look a this tutorial.

Tony
A: 

You might consider using a A& for current A. (and look into the STL's stack for the implementation

Liz Albin
I'd have +1'd if that answer actually answered the question :/
Romain
@rRomain: I thought I was answering an implicit question about allocating currentA, I suppose I'd misread the question. oh well ;)
Liz Albin
I am using the STL's stack. I just don't know how to allocate memory/free memory of my class A when I push/pop to the stack. All the examples I found are using stack<int>. I am looking for a stack<A> (a class).
n179911
You don't allocate or free memory when pushing or popping. Only when creating.
Liz Albin
+1  A: 

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...

mystack.push (myvalue);
mystack.top ();
mystack.pop ();

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...

??? = mystack.top ();
mystack.top () = ???;

To read or overwrite the top value.

These methods translate to the following calls in the underlying deque...

mydeque.push_back (myvalue);
mydeque.back ();
mydeque.pop_back ();

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.

Steve314
A: 

Assuming that A is relatively simple (even if not just a single int as your example), you can actually solve both your questions by just using a by-value stack and letting it copy and allocate the memory.

Working from your sample code:

void Main::save()
{
    aStack.push(currentA);
}

void Main::restore()
{
    currentA = aStack.top();
    aStack.pop();
}
Mark B