stack<T>

The STL stack is a container adapter that represents a last-in, first-out (LIFO) stack. Only the most-recently inserted element in the stack can be accessed.

stack is a container adapter, not a true STL container, and is implemented in terms of another linear container class like vector or deque. To explicitly specify which container to use in the stack, parametrize the stack as stack<T, ContainerType<T> >.

Common stack<T> Member Functions
void push(const T& elem)
Insert element
myStack.push(137); // Push 137 onto the stack

Pushes a new element onto the stack.

void pop();
Remove top element
myStack.pop(); // Note: no return value

Removes the top element of the stack. The behavior is undefined if the stack has no elements, so be sure not to pop off of an empty stack. Note that pop does not return a value; use top to get the value before popping.

T& top() const
const T& top() const
Return top element
int topElem = myStack.top();

Returns the top element of the stack. The behavior is undefined if the stack has no elements, so be sure not to access the top element of an empty stack. The top function returns a reference to the top element of the stack, and you can modify the element if you so choose.

size_type size() const
Get container size
int numElems = myStack.size();

Returns the number of elements stored in the stack.

bool empty() const
Is stack empty?
if(myStack.empty()) { ... }

Returns whether the stack is empty. It's considered good practice to call empty to determine whether the stack is empty rather than checking whether size() returns zero.

Other stack<T> Member Functions
Constructor: stack<T, Container<T> > (const Container<T> &initial = Container<T>())
Constructs a new stack around an existing container.
stack<int, vector<int> > myStack(myVector); // Stack contents initialized to those of myVector

Constructs a new stack whose contents are equal to those of the specified container. This constructor is rarely used, but is useful if you already have the data you want to use in the stack.