C++ Programming
STL (Standard Template Library)
Mastering stl (standard template library) concepts and implementation.
On this page
STL (Standard Template Library)
The Standard Template Library (STL) is a powerful collection of template classes and functions that provide common data structures and algorithms. It's one of C++'s greatest strengths.
What is STL?
STL consists of:
- Containers: Data structures (vector, list, map, etc.)
- Algorithms: Functions that operate on containers (sort, find, etc.)
- Iterators: Objects that traverse containers
- Function Objects: Objects that can be called like functions
Benefits:
- Efficiency: Highly optimized implementations
- Reusability: Pre-built, tested components
- Type Safety: Templates ensure type safety
- Standardization: Part of C++ standard
Containers
Sequence Containers
Store elements in linear order:
1. vector
Dynamic array that grows automatically:
1#include <vector>
2using namespace std;
3
4vector<int> v; // Empty vector
5vector<int> v2(5); // 5 elements (default initialized)
6vector<int> v3(5, 10); // 5 elements, all 10
7vector<int> v4{1, 2, 3, 4}; // Initializer list
8
9v.push_back(10); // Add element
10v.pop_back(); // Remove last element
11v.size(); // Number of elements
12v.empty(); // Check if empty
13v[0]; // Access element
14v.at(0); // Safe access (throws exception)
2. list
Doubly linked list:
1#include <list>
2using namespace std;
3
4list<int> l;
5l.push_back(10);
6l.push_front(5);
7l.pop_back();
8l.pop_front();
3. deque
Double-ended queue:
1#include <deque>
2using namespace std;
3
4deque<int> dq;
5dq.push_back(10);
6dq.push_front(5);
Associative Containers
Store elements in sorted order:
4. set
Unique elements, sorted:
1#include <set>
2using namespace std;
3
4set<int> s;
5s.insert(10);
6s.insert(5);
7s.insert(10); // Ignored (duplicate)
8s.find(10); // Returns iterator
9s.count(10); // 0 or 1
5. map
Key-value pairs, sorted by key:
1#include <map>
2using namespace std;
3
4map<string, int> m;
5m["Alice"] = 25;
6m["Bob"] = 30;
7m.insert({"Charlie", 28});
8m["Alice"]; // Access value
9m.find("Bob"); // Returns iterator
10m.count("Alice"); // 0 or 1
6. multiset / multimap
Allow duplicate keys:
1multiset<int> ms;
2ms.insert(10);
3ms.insert(10); // Allowed
Unordered Containers (C++11)
Hash-based containers (faster lookup):
7. unordered_set / unordered_map
1#include <unordered_set>
2#include <unordered_map>
3using namespace std;
4
5unordered_set<int> us;
6unordered_map<string, int> um;
Iterators
Iterators provide a way to traverse containers:
Iterator Types
- begin(): Points to first element
- end(): Points past last element
- rbegin(): Reverse begin
- rend(): Reverse end
Iterator Categories
- Input Iterator: Read-only, forward
- Output Iterator: Write-only, forward
- Forward Iterator: Read/write, forward
- Bidirectional Iterator: Forward and backward
- Random Access Iterator: Jump to any position
Using Iterators
1vector<int> v{1, 2, 3, 4, 5};
2
3// Traditional loop
4for (auto it = v.begin(); it != v.end(); ++it) {
5 cout << *it << " ";
6}
7
8// Range-based for (C++11) - preferred
9for (int num : v) {
10 cout << num << " ";
11}
12
13// With auto
14for (auto num : v) {
15 cout << num << " ";
16}
Algorithms
STL provides many algorithms in <algorithm>:
Sorting
1#include <algorithm>
2using namespace std;
3
4vector<int> v{3, 1, 4, 1, 5};
5sort(v.begin(), v.end()); // Ascending
6sort(v.begin(), v.end(), greater<int>()); // Descending
Searching
1vector<int> v{1, 2, 3, 4, 5};
2auto it = find(v.begin(), v.end(), 3);
3if (it != v.end()) {
4 cout << "Found at position: " << distance(v.begin(), it) << endl;
5}
6
7// Binary search (requires sorted container)
8bool found = binary_search(v.begin(), v.end(), 3);
Sample Output
Found at position:
Modifying Algorithms
1vector<int> v{1, 2, 3, 4, 5};
2reverse(v.begin(), v.end());
3fill(v.begin(), v.end(), 0);
4transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; });
Counting
1vector<int> v{1, 2, 2, 3, 2, 4};
2int count = count(v.begin(), v.end(), 2);
3int evenCount = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
Common STL Operations
Vector Operations
1vector<int> v;
2
3// Adding elements
4v.push_back(10);
5v.insert(v.begin(), 5);
6v.insert(v.begin() + 2, 7);
7
8// Removing elements
9v.pop_back();
10v.erase(v.begin());
11v.erase(v.begin(), v.begin() + 2);
12v.clear();
13
14// Accessing
15v[0]; // No bounds checking
16v.at(0); // Bounds checking
17v.front(); // First element
18v.back(); // Last element
19
20// Size
21v.size();
22v.empty();
23v.capacity(); // Allocated space
24v.reserve(100); // Reserve space
Map Operations
1map<string, int> m;
2
3// Inserting
4m["Alice"] = 25;
5m.insert({"Bob", 30});
6m.insert(pair<string, int>("Charlie", 28));
7
8// Accessing
9int age = m["Alice"]; // Creates if doesn't exist
10int age2 = m.at("Bob"); // Throws if doesn't exist
11
12// Checking
13if (m.find("Alice") != m.end()) {
14 // Found
15}
16
17// Iterating
18for (auto& pair : m) {
19 cout << pair.first << ": " << pair.second << endl;
20}
Sample Output
:
Function Objects (Functors)
Objects that can be called like functions:
1class Add {
2public:
3 int operator()(int a, int b) {
4 return a + b;
5 }
6};
7
8Add add;
9int result = add(5, 3); // 8
Built-in Functors
1#include <functional>
2using namespace std;
3
4plus<int> add;
5minus<int> sub;
6multiplies<int> mul;
7divides<int> div;
8modulus<int> mod;
9
10greater<int> gt;
11less<int> lt;
12equal_to<int> eq;
Lambda Functions (C++11)
Anonymous function objects:
1vector<int> v{1, 2, 3, 4, 5};
2
3// Simple lambda
4for_each(v.begin(), v.end(), [](int x) {
5 cout << x << " ";
6});
7
8// Lambda with capture
9int multiplier = 2;
10transform(v.begin(), v.end(), v.begin(), [multiplier](int x) {
11 return x * multiplier;
12});
13
14// Lambda with reference capture
15int sum = 0;
16for_each(v.begin(), v.end(), [&sum](int x) {
17 sum += x;
18});
Best Practices
- ✅ Prefer STL containers over raw arrays
- ✅ Use range-based for loops (C++11)
- ✅ Use algorithms instead of writing loops
- ✅ Choose right container for your needs
- ✅ Use const iterators when not modifying
- ✅ Reserve space for vectors when size known
- ✅ Use emplace_back (C++11) instead of push_back when possible
- ✅ Understand iterator invalidation rules
Container Selection Guide
| Need | Container |
|---|---|
| Dynamic array | vector |
| Insert at front/back | deque |
| Frequent insertions | list |
| Sorted unique elements | set |
| Key-value pairs | map |
| Fast lookup | unordered_map |
| Priority queue | priority_queue |
Common Mistakes
- ❌ Using
[]on map for non-existent key (creates it) - ❌ Iterator invalidation after container modification
- ❌ Not checking iterator before dereferencing
- ❌ Using wrong container for the use case
- ❌ Not using algorithms when available
- ❌ Forgetting to include necessary headers
Next Steps
You've now mastered the fundamentals of C++! Continue learning:
- Templates: Generic programming
- Smart Pointers: Modern memory management
- Concurrency: Multithreading
- File I/O: Reading and writing files
- Exception Handling: Error management
Summary
STL provides:
- Efficient, tested containers
- Powerful algorithms
- Type-safe templates
- Standardized interfaces
Master STL, and you'll write efficient, maintainable C++ code!
Hands-on Examples
Vector Operations
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Vector declaration and initialization
vector<int> v1;
vector<int> v2(5, 10); // 5 elements, all 10
vector<int> v3{1, 2, 3, 4, 5}; // Initializer list
// Adding elements
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
// Accessing elements
cout << "v1[0]: " << v1[0] << endl;
cout << "v1.at(1): " << v1.at(1) << endl;
cout << "v1.front(): " << v1.front() << endl;
cout << "v1.back(): " << v1.back() << endl;
// Size
cout << "Size: " << v1.size() << endl;
cout << "Empty: " << (v1.empty() ? "Yes" : "No") << endl;
// Iterating
cout << "\nElements: ";
for (int num : v1) {
cout << num << " ";
}
cout << endl;
// Using iterators
cout << "Using iterators: ";
for (auto it = v1.begin(); it != v1.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// Modifying
v1.insert(v1.begin() + 1, 15);
v1.erase(v1.begin());
cout << "\nAfter modifications: ";
for (int num : v1) {
cout << num << " ";
}
cout << endl;
return 0;
}Vector is a dynamic array that grows automatically. Use push_back to add elements, [] or at() to access. Iterators provide a way to traverse. insert() and erase() modify elements. Prefer range-based for loops for iteration.
Sample Output
v1[0]: 10 v1.at(1): 20 v1.front(): 10 v1.back(): 30 Size: 3 Empty: No Elements: 10 20 30 Using iterators: 10 20 30 After modifications: 15 30
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Array Max & Min
BeginnerFind the largest and smallest values in a C++ array in one pass, starting from INT_MIN and INT_MAX. Traces 10 5 20 15 8 and shows why starting at 0 fails.
Array Average
BeginnerCompute the average of n numbers stored in a C++ array, adding them up as they are read. Covers double for the sum, setprecision(2), and the n = 0 trap.
Merge Arrays
BeginnerMerge two integer arrays into one in C++ by copying the first array, then the second after it. Learn the n1 + i offset and how to size the merged array.
Multiplication Table
BeginnerPrint the multiplication table of any number from 1 to 10 in C++ using a for loop. Shows how the loop counter changes and why <= 10 differs from < 10.
Sum of n Natural Numbers
BeginnerAdd the numbers 1 to n in C++ with a for loop and a running total. Compare the loop with the n(n+1)/2 formula and see what happens for n = 0 or a huge n.