Q14. Demonstrate Use of STL
Question:
Write program(s) to demonstrate use of Standard Template Library (STL).
My Approach
C++ ka STL (Standard Template Library) ek powerful library hai jisme ready-made classes aur functions diye gaye hote hain.
Isme mainly 4 parts hote hain:
- Containers → Data ko hold karne ke liye (e.g.
vector,list,map,set). - Iterators → Containers ko traverse karne ke liye.
- Algorithms → Searching, sorting, reversing, etc.
- Functors → Functions jinko objects ki tarah treat kiya ja sakta hai.
Real-life example:
Mujhe agar ek news website me latest headlines ko sorted order me dikhana ho, ya apne project Sortify me files ko alphabetically arrange karna ho, to STL ka use karna sabse fast aur easy hoga.
Program Code
File Name: stl_demo.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int main() {
// 1. Vector Example
vector<int> numbers = {5, 2, 8, 1, 9};
cout << "Original Numbers: ";
for (int n : numbers) cout << n << " ";
cout << endl;
// Sort the vector
sort(numbers.begin(), numbers.end());
cout << "Sorted Numbers: ";
for (int n : numbers) cout << n << " ";
cout << endl;
// 2. Map Example
map<int, string> students;
students[101] = "Intesab";
students[102] = "Rahul";
students[103] = "Sumaira";
cout << "\nStudent Records:" << endl;
for (auto& pair : students) {
cout << "Roll No: " << pair.first << " -> Name: " << pair.second << endl;
}
// 3. Algorithm Example
int key = 8;
if (binary_search(numbers.begin(), numbers.end(), key)) {
cout << "\nElement " << key << " found in vector!" << endl;
} else {
cout << "\nElement " << key << " not found!" << endl;
}
return 0;
}Output
Before Sorting:
Original Numbers: 5 2 8 1 9After Sorting:
Sorted Numbers: 1 2 5 8 9Student Records using Map:
Roll No: 101 -> Name: Intesab
Roll No: 102 -> Name: Rahul
Roll No: 103 -> Name: SumairaSearch Example:
Element 8 found in vector!Explanation
-
Vector
- Dynamic array, jisme size automatically adjust hota hai.
- Yaha
sort()algorithm se vector ko sort kiya.
-
Map
- Key-value pairs store karta hai.
- Real life me roll no → student name mapping.
-
Algorithms
sort(),binary_search()jaise ready-made tools hote hain.- Fast, efficient aur reusable code.
Real-Life Scenario
- E-commerce website me products ko sort karne ke liye
sort(). - Cybersecurity logs ko filter karne ke liye
mapyaset. - Talkum (chat app) me users ke messages ko map ke form me store karna (user_id → message).
Conclusion
STL se C++ programming fast aur efficient hoti hai.
Yeh library har tarah ke data structures aur algorithms provide karti hai jisse code likhne ka time kam ho jata hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live