C++ STL Introduction
The C++ Standard Template Library, usually called the STL, is a collection of reusable containers, algorithms, and helper tools. It helps you store data, process data, and write less custom code for common programming tasks.
Instead of building your own dynamic array, sorting function, or search loop every time, you can use well-tested tools from the standard library.
Main Parts of the STL
The STL is large, but beginners can think about it in three main parts:
- Containers store data. Examples include
std::vector,std::list,std::map, andstd::set. - Algorithms perform work on data. Examples include
std::sort,std::find, andstd::count. - Iterators point to positions inside containers. Algorithms use iterators to know where to start and stop.
Most STL names are in the std namespace, so examples use names such as std::vector and std::sort.
Example
This program stores scores in a std::vector, sorts them with std::sort, and prints the result.
#include <algorithm>
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> scores = {82, 95, 70, 88};
std::sort(scores.begin(), scores.end());
for (int score : scores) {
std::cout << score << std::endl;
}
return 0;
}
Output:
70
82
88
95
How It Works
#include <vector> gives the program access to std::vector. A vector is a container that stores a sequence of values and can grow as needed.
#include <algorithm> gives the program access to algorithms such as std::sort. The call std::sort(scores.begin(), scores.end()) sorts the values from the beginning of the vector up to its end.
The expressions scores.begin() and scores.end() produce iterators. You can think of them as markers for the range of elements that the algorithm should use.
Why Templates Matter
The STL uses templates, which means many tools work with different data types. For example, std::vector<int> stores integers, while std::vector<std::string> stores strings. The container is still a vector, but the element type changes.
This is why STL names often contain angle brackets. The type inside the brackets tells C++ what kind of value the tool should store or process.
Common STL Headers
| Header | What it provides |
|---|---|
<vector> |
std::vector, a resizable array-like container |
<string> |
std::string, the standard text type |
<algorithm> |
Algorithms such as std::sort and std::find |
<map> |
std::map, a key-value container |
<set> |
std::set, a container of unique sorted values |
When To Use the STL
Use the STL when you need a common data structure or operation. It is usually clearer and safer to use std::vector than to manually manage a dynamic array, and it is usually better to use std::sort than to write a sorting algorithm yourself.
The next STL lessons introduce specific containers and algorithms one at a time, starting with the tools you are most likely to use in everyday C++ programs.
