The Standard Template Library (STL)
Ready-made containers and algorithms, so you don't reinvent the wheel
std::vector and std::map and algorithms like std::sort — tested, fast, and ready to use.
- store a growing list of values in a
std::vector, - look things up by key with a
std::map, - use ready-made algorithms like
sort,find, andcount, - loop over any container with a clean range-based for.
1. What is the STL?
The Standard Template Library is a collection of ready-to-use tools built into C++. You get it for free — you just #include the right header. It has three main kinds of tools:
- Containers — objects that hold your data (like
vectorandmap). - Algorithms — ready-made operations that work on your data (like
sort,find,count). - Iterators — the "pointers" that connect algorithms to containers (you'll see
.begin()and.end()).
2. std::vector — a list that grows
A plain C++ array has a fixed size. A std::vector is a smarter array that can grow and shrink while your program runs. You add items with push_back, ask how many there are with size(), and read any item with square brackets [i] (starting at index 0).
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> scores; // an empty, resizable list of ints
scores.push_back(90); // add items to the end
scores.push_back(75);
scores.push_back(88);
cout << "We have " << scores.size() << " scores\n";
cout << "First score: " << scores[0] << "\n";
return 0;
}
Output:
We have 3 scores
First score: 90
Notice we never said how big the vector was — it grew by itself as we pushed items in.