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:

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.

Main.cpp
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.

Main.cpp
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

Step-by-Step Process

  1. Use a while loop with push_back.
  2. Apply sort(v.begin(), v.end(), greater<int>()).
  3. Print the first 3 elements of the sorted vector.

Expected Deliverables

Solve in Compiler