The C++ Standard Template Library (STL) offers ready-made implementations of core data structures like stack, queue, and priority queue. These containers are extremely useful for real-world problem-solving and competitive programming.
In this blog, you’ll learn how to use them with simple examples and expected outputs.
Stack, Queue, and Priority Queue in C++ STL: Explained with Code and Output
1. Stack in C++
A stack follows the Last-In-First-Out (LIFO) principle. The last element added is the first one removed.
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int>st;
st.push(10);
st.push(20);
st.push(30);
cout<<"Top: "<<st.top()<<endl;
st.pop();
cout<<"After pop, top: " <<st.top()<<endl;
return 0;
}
Output: Top: 30 After pop, top: 20
Key Functions:
-
push(x)– adds an element -
pop()– removes the top element -
top()– returns the top element -
empty()– checks if the stack is empty -
size()– returns the number of elements
2. Queue in C++
A queue follows the First-In-First-Out (FIFO) principle. The first element added is the first one removed.
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string>q;
q.push("Alice");
q.push("Bob");
q.push("Charlie");
cout<<"Front: "<<q.front()<<endl;
cout<<"Back: "<<q.back()<<endl;
q.pop();
cout<<"After pop, front: "<<q.front()<<endl;
return 0;
}
Output: Front: Alice Back: Charlie After pop, front: Bob
-
push(x)– adds element at back -
pop()– removes element from front -
front()– returns front element -
back()– returns last element -
empty()– checks if queue is empty
3. Priority Queue in C++
A priority queue stores elements in such a way that the largest element is always at the top by default (Max-Heap).
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq;
pq.push(50);
pq.push(10);
pq.push(30);
cout<<"Top element: " <<pq.top()<<endl;
pq.pop();
cout<<"After pop, top element: " <<pq.top()<<endl;
return 0;
}
Output: Top element: 50 After pop, top element: 30