Module 23: Standard Template Library (STL)
The Standard Template Library (STL) is one of the most powerful features of C++. It provides a collection of ready-to-use generic classes and functions for storing, processing, and manipulating data efficiently.
Instead of writing your own data structures and algorithms, STL provides optimized implementations that save development time and improve code quality.
The STL consists of four main components:
- Containers
- Iterators
- Algorithms
- Function Objects (Functors)
Modern C++ also extensively uses Lambda Expressions and Smart Pointers, making STL even more powerful.
STL Architecture
1 STL 2 │ 3 ┌────────────┼────────────┐ 4 │ │ │ 5Containers Iterators Algorithms 6 │ │ │ 7 └────────────┼────────────┘ 8 │ 9 Functors 10 │ 11 Lambda Expressions
1. Containers
Containers store collections of objects.
Types of Containers
Sequence Containers
- vector
- array
- deque
- list
- forward_list
Associative Containers
- set
- multiset
- map
- multimap
Unordered Containers
- unordered_set
- unordered_map
- unordered_multiset
- unordered_multimap
Container Adaptors
- stack
- queue
- priority_queue
Vector
A vector is a dynamic array that automatically resizes.
Example
1#include <iostream> 2#include <vector> 3 4using namespace std; 5 6int main() 7{ 8 vector<int> numbers = {10,20,30,40}; 9 10 for(int value : numbers) 11 { 12 cout << value << " "; 13 } 14 15 return 0; 16}
Output
110 20 30 40
List
A list is a doubly linked list.
1#include <list> 2#include <iostream> 3 4using namespace std; 5 6int main() 7{ 8 list<int> values = {5,10,15}; 9 10 for(int x : values) 11 cout << x << " "; 12}
Output
15 10 15
Map
Stores key-value pairs.
1#include <iostream> 2#include <map> 3 4using namespace std; 5 6int main() 7{ 8 map<int,string> students; 9 10 students[1]="Ankit"; 11 students[2]="Rahul"; 12 13 cout << students[1]; 14 15 return 0; 16}
Output
1Ankit
Set
Stores unique values.
1#include <iostream> 2#include <set> 3 4using namespace std; 5 6int main() 7{ 8 set<int> numbers = {5,2,3,2,5,1}; 9 10 for(int x : numbers) 11 cout << x << " "; 12}
Output
11 2 3 5
Stack
LIFO (Last In First Out)
1#include <stack> 2#include <iostream> 3 4using namespace std; 5 6int main() 7{ 8 stack<int> s; 9 10 s.push(10); 11 s.push(20); 12 13 cout << s.top(); 14}
Output
120
Queue
FIFO (First In First Out)
1#include <queue> 2#include <iostream> 3 4using namespace std; 5 6int main() 7{ 8 queue<int> q; 9 10 q.push(10); 11 q.push(20); 12 13 cout << q.front(); 14}
Output
110
2. Iterators
Iterators are objects that allow traversal of container elements.
Common Iterators
- begin()
- end()
- rbegin()
- rend()
- cbegin()
- cend()
Example
1#include <iostream> 2#include <vector> 3 4using namespace std; 5 6int main() 7{ 8 vector<int> nums = {10,20,30}; 9 10 for(auto it = nums.begin(); it != nums.end(); it++) 11 { 12 cout << *it << " "; 13 } 14 15 return 0; 16}
Output
110 20 30
3. Algorithms
The <algorithm> library provides many useful algorithms.
Popular algorithms include:
- sort()
- find()
- reverse()
- count()
- max_element()
- min_element()
- binary_search()
sort()
1#include <iostream> 2#include <algorithm> 3#include <vector> 4 5using namespace std; 6 7int main() 8{ 9 vector<int> nums={5,1,4,2}; 10 11 sort(nums.begin(), nums.end()); 12 13 for(int x : nums) 14 cout << x << " "; 15}
Output
11 2 4 5
reverse()
1reverse(nums.begin(), nums.end());
find()
1auto it = find(nums.begin(), nums.end(), 20);
4. Functors
A functor is an object that behaves like a function.
Example
1#include <iostream> 2 3using namespace std; 4 5class Square 6{ 7public: 8 int operator()(int x) 9 { 10 return x*x; 11 } 12}; 13 14int main() 15{ 16 Square sq; 17 18 cout << sq(5); 19}
Output
125
5. Lambda Expressions
Lambdas are anonymous functions introduced in C++11.
Syntax
1[capture](parameters) 2{ 3 // body 4};
Example
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 auto square=[](int x) 8 { 9 return x*x; 10 }; 11 12 cout << square(8); 13}
Output
164
Lambda with sort()
1sort(nums.begin(), nums.end(), 2[](int a,int b) 3{ 4 return a>b; 5});
Sorts in descending order.
6. Smart Pointers
Smart pointers automatically manage memory.
Types
- unique_ptr
- shared_ptr
- weak_ptr
unique_ptr
1#include <iostream> 2#include <memory> 3 4using namespace std; 5 6int main() 7{ 8 unique_ptr<int> ptr=make_unique<int>(100); 9 10 cout<<*ptr; 11}
Output
1100
shared_ptr
1shared_ptr<int> p1 = make_shared<int>(50); 2 3shared_ptr<int> p2 = p1;
Memory is deleted automatically when all owners are destroyed.
weak_ptr
Used to observe shared objects without increasing the reference count.
Common STL Headers
| Header | Purpose |
|---|---|
<vector> | Dynamic array |
<list> | Linked list |
<deque> | Double-ended queue |
<queue> | Queue |
<stack> | Stack |
<set> | Unique elements |
<map> | Key-value pairs |
<unordered_map> | Hash map |
<algorithm> | Algorithms |
<iterator> | Iterators |
<memory> | Smart pointers |
Best Practices
- Use
vectoras the default sequence container. - Use range-based
forloops where possible. - Prefer STL algorithms over manual loops.
- Use lambda expressions for short operations.
- Use smart pointers instead of raw pointers.
- Choose the appropriate container based on performance requirements.
Practice Problems
- Store 10 numbers in a vector and print them.
- Sort numbers in ascending and descending order.
- Find the maximum element in a vector.
- Count duplicate elements using a map.
- Reverse a list using STL algorithms.
- Create a priority queue.
- Sort custom objects using a lambda expression.
- Manage dynamic memory using
unique_ptr. - Build a student database using
map. - Compare the performance of
vectorandlist.
Interview Questions
- What is the Standard Template Library (STL)?
- What are the main components of STL?
- What is the difference between
vectorandlist? - What is the difference between
mapandunordered_map? - What are iterators?
- What are STL algorithms?
- What are functors?
- What are lambda expressions?
- What are smart pointers?
- Why is
unique_ptrpreferred over raw pointers? - When should you use
shared_ptr? - What is the purpose of
weak_ptr?
Summary
In this module, you learned:
- What the Standard Template Library (STL) is and why it is important.
- How to use sequence, associative, unordered, and adaptor containers.
- How iterators provide a uniform way to traverse containers.
- How STL algorithms simplify common operations like sorting and searching.
- How functors and lambda expressions improve flexibility.
- How smart pointers provide automatic memory management and prevent memory leaks.
Next Module: Module 24: Modern C++ (C++11, C++14, C++17, C++20 & C++23) — auto, nullptr, Range-based for, Move Semantics, Structured Bindings, constexpr, Concepts, Modules, Coroutines, and other modern language features.