Day 2 – Standard Template Library (STL) in C++

Today I focused on understanding the Standard Template Library (STL) in C++. STL provides a set of ready-to-use classes and functions like containers, algorithms, functions, and iterators to simplify and speed up coding.

STL Overview

STL consists of:

  • Containers: Store data (e.g., vector, list, stack)

  • Algorithms: Operations like sort, find, etc.

  • Functions: Useful utilities (e.g., swap, max, min)

  • Iterators: Bridge between containers and algorithms


1. Pairs

  • Used to group two values.

  • Can be nested.

#include <utility>
pair<int, int> p = {1, 2};
pair<int, pair<int, int>> nested = {1, {2, 3}};
cout << p.first << " " << p.second;

2. Vector

  • Dynamic array (singly linked internally).

  • Supports random access and growth.

#include <vector>
vector<int> v;
v.push_back(10);
v.emplace_back(20);
cout << v.back(); // 20
cout << v.size();//2

for (auto it = v.begin(); it != v.end(); ++it)
    cout << *it;

for (int x : v)
    cout << x;

v.insert(v.begin(), 5);//{5,10,20}
v.erase(v.begin());//{10,20}

3. List

  • Doubly linked list internally.

  • Efficient front/back operations.

  • Different from vectors as front functions are also performed and has a better time complexity.

#include <list>
list<int> l;
l.push_back(1);
l.push_front(0);
l.emplace_back(2);
l.emplace_front(-1);

for (int x : l)
    cout << x;

4. Deque

  • Double-ended queue.

  • Supports insertion/deletion from both ends.

#include <deque>
deque<int> dq;
dq.push_back(1);
dq.push_front(0);
dq.pop_back();
dq.pop_front();

5. Stack

  • LIFO (Last-In-First-Out)

  • All operations are O(1)

#include <stack>
stack<int> st;
st.push(1);
st.emplace(2);
cout << st.top(); // 2
st.pop();
cout << st.empty(); // 0 or 1
cout << st.size();

6. Queue

  • FIFO (First-In-First-Out)

  • All operations are O(1)

#include <queue>
queue<int> q;
q.push(1);
q.emplace(2);
cout << q.front();
q.pop();

7. Priority Queue

  • Default: Max-heap

  • Can create min-heap with custom comparator

#include <queue>
priority_queue<int> pq; // max-heap,descending order
pq.push(5);
pq.push(10);// O(log n)
pq.pop(); // O(log n),10 will be popped here
cout << pq.top(); // O(1)

priority_queue<int, vector<int>, greater<int>> min_pq; // min-heap,ascending order
min_pq.push(5);
min_pq.push(1);
cout << min_pq.top(); // 1

Summary

  • STL simplifies coding by providing standard containers and algorithms.

  • Understanding time complexity (e.g., O(1), O(log n)) is key for optimization.

  • Practiced syntax and basics for each structure.

No theory covered today — will add later.

0
Subscribe to my newsletter

Read articles from Siddharth Gandhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Siddharth Gandhi
Siddharth Gandhi