Chapter 8 — The Standard Template Library (STL)
📚 Chapter Overview
Real-world C++ developers don't rewrite common algorithms and data structures. In this chapter, you will master the STL, a collection of powerful tools for managing dynamic lists, maps, and high-performance sorting/searching.
Learning Objectives:
- Master
std::vectorfor dynamic arrays. - Use
std::mapfor key-value storage. - Apply built-in STL Algorithms like
sort().
8.1 Vectors: Dynamic Arrays
Part 1 — Definition
A Vector is a sequence container that represents an array that can change in size. Unlike built-in arrays, vectors manage their own memory automatically. When you add an item, the vector grows; when you remove one, it shrinks.
Part 2 — Syntax
#include <vector>
vector<int> v;
v.push_back(10); // Add
v.pop_back(); // Remove last
Part 3 — Example
Problem: Store a dynamic list of prices and calculate their total.
vector<double> prices = {10.5, 20.0, 5.75};
prices.push_back(15.2);
double total = 0;
for(double p : prices) {
total += p;
}
cout << "Total: " << total;
Part 4 — Video
Video: Coming Soon
8.2 STL Algorithms (Sort & Search)
Part 1 — Definition
The STL provides a rich set of Algorithms that operate on containers. Instead of writing your own sorting logic, you can use std::sort(). These algorithms are highly optimized and work with any container type.
Part 2 — Syntax
#include <algorithm>
sort(v.begin(), v.end()); // Sorts ascending
reverse(v.begin(), v.end()); // Reverses
Part 3 — Example
Problem: Take 5 names from the user and sort them alphabetically.
vector<string> names(5);
for(int i=0; i<5; i++) cin >> names[i];
sort(names.begin(), names.end());
for(string n : names) cout << n << " ";
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Student Ranker" using Vectors and Algorithms.
Requirements
- Store a dynamic list of marks using
vector<int>. - Take marks until the user enters -1.
- Sort the marks in descending order (Highest to Lowest).
- Identify the Top 3 scores.
Step-by-Step Process
- Use a
whileloop withpush_back. - Apply
sort(v.begin(), v.end(), greater<int>()). - Print the first 3 elements of the sorted vector.
Expected Deliverables
student_ranker.cppsource file.