Standard Template Library in C++

By Shakib Ansari | Date: Mon, Jun 2, 2025

C++ ki Standard Template Library (STL) ek aisi library hai jo hume reusable, efficient, aur generic data structures aur algorithms deti hai. Iska use karna time-saving hota hai, especially jab aapko fast and error-free development chahiye.

1. Introduction to STL

STL ke 4 main components hote hain:

Containers: Data ko store karte hain (vector, map, etc.)

Algorithms: Data par operation karte hain (sort, find, etc.)

Iterators: Containers ko traverse karne ke liye.

Functions: Utility functions like bind, function etc. (C++11+)

2. Commonly Used Containers

Vector (Dynamic Array)

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3};
    v.push_back(4);
    for(int i : v) cout << i << " ";
    return 0;
}

Output:

1 2 3 4

List (Doubly Linked List)

#include <list>
list<int> l = {10, 20, 30};
l.push_front(5); // 5 10 20 30

Map (Key-Value Pair, Sorted by Key)

#include <map>
map<string, int> age;
age["Amit"] = 25;
age["Neha"] = 22;

Set (Unique, Sorted Elements)

#include <set>
set<int> s = {3, 1, 4, 1};  // Output: 1 3 4

Stack (LIFO)

#include <stack>
stack<int> st;
st.push(10);
st.push(20);
st.pop(); // Removes 20

Queue (FIFO)

#include <queue>
queue<int> q;
q.push(100);
q.push(200);
q.pop(); // Removes 100

3. Iterators in STL

Iterators containers ko access karne ke liye pointers ki tarah kaam karte hain.

vector<int> v = {1, 2, 3};
for(auto it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
}

4. STL Algorithms

STL mein kai useful algorithms milte hain:

#include <algorithm>
vector<int> v = {5, 3, 8, 1};
sort(v.begin(), v.end()); // 1 3 5 8

int index = find(v.begin(), v.end(), 5) - v.begin();
reverse(v.begin(), v.end());  // 8 5 3 1

STL Ka Faayda?

  • Reusable: Code ko baar-baar likhne ki zarurat nahi
  • Time-efficient: Optimized internal implementation
  • Debugging Easy: Less chances of bugs in logic

Question 1: Frequency Counter using Map

Problem:

Write a C++ program that takes n integers from the user and prints the frequency of each number using an STL map.

Input Example:

n = 6  
Numbers = 1 2 2 3 3 3

Expected Output:

1 -> 1 times  
2 -> 2 times  
3 -> 3 times
Use map<int, int> to count frequencies.

Question 2: Unique Sorted Elements using Set

Problem:

Take a list of n integers (some may be duplicates). Use an STL set to store and display all unique elements in sorted order.

Input Example:

n = 7  
Numbers = 4 2 5 2 4 3 1

Expected Output:

1 2 3 4 5
Use set<int> to automatically sort and remove duplicates.
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments