# 3.5. Using a Stack in C++ΒΆ

Now that we have clearly defined the stack as an abstract data type we will turn our attention to using a stack with the help of the Standard Template Library (STL) in C++. Recall that when we give an abstract data type a physical implementation we refer to the implementation as a data structure.

As we described in Chapter 1, in C++, as in any object-oriented programming language, the implementation of choice for an abstract data type such as a stack is the creation of a new class. The stack operations are implemented as methods. However, the STL already has a well written implementation of the Stack class.

The following stack implementation (ActiveCode 1) assumes that
the end of the array will hold the top element of the stack. As the stack
grows (as `push`

operations occur), new items will be added on the end
of the array. `pop`

operations will manipulate that same end.

Self Check

- 5
- Remember that a stack is built from the bottom up.
- 12
- pay attention to the line that says m.pop();.
- 27
- Good job. This is correct because the 12 was poped of from the end and the 27 was pushed.
- The stack is empty
- This would mean everyting is removed from the stack, when does that happen?

Q-3: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?

```
stack<int> m;
m.push(5);
m.push(12);
m.pop();
m.push(27);
cout << m.top();
```

- 37
- You may want to check out the docs for
- the stack is empty
- There is an odd number of things on the stack but each time through the loop 2 things are popped.
- an error will occur
- Good Job, this is true because the stack can not evenly pop off every item within itself, because there is an odd number of items.
- 4
- You may want to check out the docs for isEmpty

Q-4: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?

```
stack<int> m;
m.push(37);
m.push(56);
m.push(4);
while (!m.empty()){
m.pop();
m.pop();
}
```