STL Intro
Overview
In the 1990s, C++ engineers were constantly rewriting their own code for dynamic arrays, Linked Lists, and sorting algorithms. This was slow, bug-prone, and non-standardized.
The Standard Template Library (STL) was introduced to solve this. It is a massive, heavily-optimized library of pre-written Data Structures (Containers) and Algorithms included with every C++ compiler. It relies heavily on C++ 'Templates', meaning a single std::vector can instantly adapt to hold ints, doubles, or custom Player objects without rewriting any code. Mastering the STL is the absolute most important step to becoming a professional C++ developer.
Syntax
// The STL is broken into 3 primary components:
//
// 1. CONTAINERS: Pre-built Data Structures
// - vector, list, map, set, queue, stack
//
// 2. ALGORITHMS: Pre-built Logic
// - sort, find, reverse, binary_search
//
// 3. ITERATORS: The Bridge
// - Special pointers that allow Algorithms to securely
// travel through Containers without knowing how they are built.Common Pitfalls
- Reinventing the wheel. If you are writing a custom Bubble Sort algorithm in a production C++ application, you are doing it wrong. The STL's
std::sort()was written by world-class engineers, uses a highly optimized Introsort (QuickSort + HeapSort), and will mathematically obliterate any custom sort loop you write.
Interview Questions
.sort() method inside the Vector class?By physically decoupling them, the STL achieves monumental code reuse. Instead of writing 20 different sorting functions for 20 different data structures, the STL engineers wrote a single std::sort function that uses Iterators. Because it uses Iterators, that single algorithm can instantly sort a Vector, a Deque, or a raw C-array seamlessly.
Real-World Example
Using all 3 pillars of the STL (Containers, Iterators, and Algorithms) in exactly two lines of code.
#include <iostream>
#include <vector> // CONTAINER
#include <algorithm> // ALGORITHMS
int main() {
std::vector<int> data = {50, 10, 90, 20};
// std::sort is the ALGORITHM
// data.begin() and data.end() provide the ITERATORS
std::sort(data.begin(), data.end());
// Array is now: {10, 20, 50, 90}
return 0;
}Check Your Knowledge
Test your understanding of STL Intro with these quick questions.