4.3.2 Basic Stack

Stacks

A stack is an advanced data structure in C++. It is part of the standard library but does need to be included to use it.

#include <stack>

A stack stores a list of values like a vector, however unlike vectors, you only have access to one item at a time. For a stack, this is the last item that you put into the stack, which is why stacks are described as last-in. first-out.

Creating a Stack

Stacks can be declared as an empty stack with a variable type, similar to how a new vector is declared. Once declared, they are empty but ready to be added to.

stack<int> intStack; // creates a new int stack
stack<string> strStack; // creates a new string stack

Stacks can also be declared and initialized with an existing data structure such as a vector.

vector<int> numVector {1,2,3,4};
stack<int> numStack (numVector);

Basic Stack Operations

As mentioned above, stacks store values but only give you access to the top item. As a result, the operations with stacks are pretty limited.

FunctionOperation

push

Inserts new element to the top of the stack.

top

Accesses the element on the top of the stack, but does not remove it.

pop

Removes the element on the top of the stack, but does not return it.

size

Returns the number of items in the stack.

empty

Returns a bool as true if the stack is empty.

There are a couple of things to notice when looking at stack functions. First, unlike Java, C++ separates the access and remove functions. If you want to see the top item in a stack, you use the top command, but the item will remain on top of the stack. To remove an item, you use the pop command, but this doesn’t return any value. Often times you may want to see and remove the item. Many languages have a single command for this, but in C++, you need to use both the top, then the pop commands.

Also, you will notice that there is a size and an empty function. While it is possible to use size == 0, this can be streamlined with the empty function.

Iterating through a Stack

If you are asking yourself how do I iterate through a stack, the answer is you don’t. Stacks have a very specific purpose and limited functionality that only allows access to the top value. If you need functionality to see different items in the list, then you should not use a stack.

Last updated