Search⌘ K

STL Classes

Explore essential STL classes in C++ that are important for coding interviews. Understand how to use stack, queue, priority queue, multimap, and set, along with their key functions, to efficiently solve common data structure problems.

We'll cover the following...

Stack

Stacks are a type of data structure with last in first out (LIFO) order. A new element is added at the top and removed from that end only.

The functions supported by stacks are:

empty() – Returns whether the stack is empty or not.

size() – Returns the size of the stack.
 
top() – Returns a reference to the top most element of the stack.
 
push(i) – Insert an element 'i' at the top of the stack.
 
pop() – Deletes the top most element of the stack 
C++
#include <iostream>
#include <stack>
using namespace std;
void print(stack <int> myStack) {
stack < int > tempStack = myStack;
while (tempStack.empty() == false) {
cout << " " << tempStack.top();
tempStack.pop();
}
cout << endl;
}
int main () {
stack <int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
cout << "myStack is : ";
print(myStack);
cout << "myStack.size() : " << myStack.size() << endl;
cout << "myStack.top() : " << myStack.top() << endl;
cout << "myStack.pop() : popping top object" << endl;
myStack.pop();
cout << "myStack is : ";
print(myStack);
return 0;
}

Queue

Queues are container adaptors which operate in a first in first out (FIFO) order. Elements are inserted at the back (end) and are deleted from the front. You can read more ...