← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 13 of 15

C++ stack STL

What is std::stack?

std::stack is a container adapter that provides Last-In-First-Out (LIFO) access. It wraps an underlying container (deque by default) and restricts access so elements can only be added or removed from the top.

Example: What is std::stack?

cpp
#include <iostream>
#include <stack>

int main() {
	std::stack<int> s; // LIFO container adapter
	s.push(1);
	s.push(2);
	std::cout << s.top() << std::endl;
	return 0;
}

push(), pop() and top()

push() adds an element to the top. top() returns a reference to the top element without removing it. pop() removes the top element but does not return its value -- read it with top() first if you need it.

Example: push(), pop() and top()

cpp
#include <iostream>
#include <stack>

int main() {
	std::stack<int> s;
	s.push(10);
	std::cout << s.top() << std::endl; // returns without removing
	s.pop(); // removes without returning
	std::cout << s.size() << std::endl;
	return 0;
}

LIFO Behavior

The defining property of a stack is that the most recently pushed element is always the first one popped -- Last In, First Out. This makes it ideal for undo operations, function call tracking, and expression parsing.

Example: LIFO Behavior

cpp
#include <iostream>
#include <stack>

int main() {
	std::stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);
	std::cout << s.top() << std::endl; // most recently pushed comes out first
	return 0;
}

Checking empty() and size()

empty() returns true if the stack has no elements. size() returns the current element count. Always check empty() before calling top() or pop() to avoid undefined behavior.

Example: Checking empty() and size()

cpp
#include <iostream>
#include <stack>

int main() {
	std::stack<int> s;
	if (s.empty()) { // check before calling top()/pop() on an empty stack
		std::cout << "Empty" << std::endl;
	}
	std::cout << s.size() << std::endl;
	return 0;
}

Practical Use: Balanced Parentheses

A classic stack use case is checking whether brackets in an expression are balanced -- push opening brackets, and pop and compare when a closing bracket is seen.

Example: Practical Use: Balanced Parentheses

cpp
#include <iostream>
#include <stack>
#include <string>

int main() {
	std::string expr = "(()())";
	std::stack<char> s;
	bool balanced = true;
	for (char c : expr) {
		if (c == '(') s.push(c);
		else if (!s.empty()) s.pop();
		else balanced = false;
	}
	std::cout << (balanced && s.empty()) << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.