Loading lessons...
The Standard Template Library: Organisation, Containers, Iterators & Allocators
The Standard Template Library: Organisation, Containers, Iterators & Allocators
The Standard Template Library (STL) is the part of the C++ standard library that provides ready-made, generic data structures and algorithms, all built with templates. Developed by Alexander Stepanov and Meng Lee at Hewlett-Packard and adopted into standard C++ in 1994-1998, it lets a program use a dynamic array, a linked list, a set or a map, and sort or search them, without writing any of that code by hand. This lesson explains how the library is organised; the next three lessons use its parts.
1. Components of the STL
The STL has three core components, plus two supporting ones.
| Component | What it is | Examples |
|---|---|---|
| Containers | objects that store data (class templates) | vector, list, deque, set, map, stack |
| Algorithms | procedures that process the data in containers (function templates) | sort, find, count, copy, reverse |
| Iterators | objects that point to elements, like pointers, and connect algorithms to containers | vector<int>::iterator, list<string>::iterator |
| Function objects | objects that act like functions, used to customise algorithms | less<int>, greater<int>, user functors |
| Allocators | objects that manage memory for containers | allocator<T> (the default) |
Algorithms reach container elements through iterators
The key design idea: algorithms do not work on containers directly. They work on ranges of iterators. So sort is written once and works for any container whose iterators support what sort needs; and a new container works with all existing algorithms as long as it provides iterators.
2. Library Organisation: Headers
| Header | Contents |
|---|---|
<vector>, <list>, <deque> | sequence containers |
<set>, <map> | associative containers (set, multiset, map, multimap) |
<stack>, <queue> | container adaptors (stack, queue, priority_queue) |
<algorithm> | most algorithms |
<numeric> | numeric algorithms (accumulate, inner_product, ...) |
<iterator> | iterator utilities (ostream_iterator, back_inserter, ...) |
<functional> | function objects (plus, less, greater, ...) |
<memory> | allocators |
<utility> | pair, make_pair |
Everything is in namespace std.
3. Containers
A container is an object that holds other objects (its elements). Each container is a class template, so it can hold any type: vector<int>, vector<string>, list<Student>.
| Category | Containers | Organisation | Typical use |
|---|---|---|---|
| Sequence containers | vector, deque, list | elements kept in a linear order decided by where they were inserted | lists of items in a given order |
| Associative containers | set, multiset, map, multimap | elements kept sorted by key (in a balanced tree) for fast search | lookup by key, unique collections |
| Derived containers (adaptors) | stack, queue, priority_queue | built on top of a sequence container with a restricted interface | LIFO, FIFO, highest-priority-first |
The standard containers at a glance
| Container | Header | Structure | Iterator | Notes |
|---|---|---|---|---|
vector | <vector> | dynamic array | random access | fast insert/delete at the back; [] indexing |
deque | <deque> | double-ended queue | random access | fast insert/delete at both ends |
list | <list> | doubly linked list | bidirectional | fast insert/delete anywhere; no [] |
set | <set> | sorted unique keys | bidirectional | fast lookup; no duplicates |
multiset | <set> | sorted keys, duplicates allowed | bidirectional | |
map | <map> | sorted key → value pairs, unique keys | bidirectional | m[key] access |
multimap | <map> | key → value, duplicate keys allowed | bidirectional | |
stack | <stack> | LIFO on a deque (default) | none | push, pop, top |
queue | <queue> | FIFO on a deque (default) | none | push, pop, front, back |
priority_queue | <queue> | heap on a vector (default) | none | top is always the largest |
Members common to all containers
| Member | Meaning |
|---|---|
| default, copy constructors; destructor | create, copy and destroy containers |
size() | number of elements |
empty() | true if no elements |
max_size() | largest possible number of elements |
swap(c) | exchange contents with another container |
=, ==, !=, <, ... | assignment and comparison |
begin(), end() | iterators to the first element and one past the last (not for adaptors) |
clear(), insert(), erase() | (sequence and associative containers) |
Choosing a container
| If you need... | Use |
|---|---|
| fast access by index, adding at the end | vector |
| adding/removing at both ends | deque |
| frequent insertion/deletion in the middle | list |
| unique, sorted values; fast "is it there?" | set |
| lookup of a value by a key | map |
| LIFO / FIFO / priority behaviour | stack / queue / priority_queue |
4. Iterators
An iterator is an object that points to an element in a container and can move to other elements. It behaves like a pointer: *it gives the element, ++it moves to the next one, it1 == it2 compares positions. Each container defines its own iterator type, e.g. vector<int>::iterator.
Every container (except the adaptors) provides:
begin(): an iterator to the first element;end(): an iterator one past the last element (it does not point to an element; it marks the end).
A range [first, last) includes first but not last. So [c.begin(), c.end()) is the whole container, and an empty container has begin() == end().
#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main() {
vector<int> v;
for (int i = 1; i <= 5; i++) {
v.push_back(i * 10);
}
vector<int>::iterator it;
cout << "vector:";
for (it = v.begin(); it != v.end(); ++it) { // the classic iterator loop
cout << " " << *it;
}
cout << endl;
it = v.begin() + 2; // random access: jump ahead
*it = 99; // change the element it points to
cout << "v[2] is now " << v[2] << endl;
list<char> l;
l.push_back('a');
l.push_back('b');
l.push_back('c');
cout << "list backwards:";
for (list<char>::reverse_iterator r = l.rbegin(); r != l.rend(); ++r) {
cout << " " << *r;
}
cout << endl;
const vector<int>& cv = v;
vector<int>::const_iterator ci = cv.begin(); // read-only iterator
cout << "first via const_iterator: " << *ci << endl;
return 0;
}Output:
vector: 10 20 30 40 50
v[2] is now 99
list backwards: c b a
first via const_iterator: 10Iterator categories
Different containers support different movements, so iterators come in five categories. Each algorithm states which category it needs: sort needs random access, so it works on vector and deque but not on list (which has its own sort() member).
| Category | Can do | Provided by |
|---|---|---|
| Input | read forward once (*it, ++) | istream_iterator |
| Output | write forward once | ostream_iterator, back_inserter |
| Forward | read and write, forward, multiple passes | (hash containers in later standards) |
| Bidirectional | forward and backward ( - ) | list, set, map, multiset, multimap |
| Random access | jump by any amount (it + n, it[n], <) | vector, deque, ordinary pointers |
Each category includes all the abilities of the ones above it: random access ⊃ bidirectional ⊃ forward ⊃ input/output.
The five iterator categories
Stream iterators
Iterators can also be attached to streams, which lets algorithms read from cin or print to cout:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main() {
int a[5] = {5, 3, 9, 1, 7};
vector<int> v(a, a + 5); // construct from a range of pointers
sort(v.begin(), v.end());
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); // print through an iterator
cout << endl;
return 0;
}Output:
1 3 5 7 9 Ordinary pointers are random-access iterators, so algorithms work on plain arrays too: sort(a, a + 5).
5. Allocators
An allocator is an object that handles memory allocation and deallocation for a container. Every container has an allocator template parameter, which defaults to std::allocator<T>:
template <class T, class Allocator = allocator<T> >
class vector;So vector<int> is really vector<int, allocator<int> >. The default allocator uses new and delete.
A program can supply its own allocator, for example to take memory from a pre-allocated pool, from shared memory, or to count allocations, without changing the container code. This separates memory management from the data structure, just as iterators separate algorithms from containers.
| Allocator member | Task |
|---|---|
allocate(n) | get raw memory for n objects of type T |
deallocate(p, n) | return that memory |
construct(p, value) | build an object at p (C++98) |
destroy(p) | call the destructor of the object at p (C++98) |
#include <iostream>
#include <memory>
using namespace std;
int main() {
allocator<int> alloc;
int* p = alloc.allocate(3); // raw memory for 3 ints
for (int i = 0; i < 3; i++) {
alloc.construct(p + i, (i + 1) * 100);
}
for (int i = 0; i < 3; i++) {
cout << p[i] << " ";
}
cout << endl;
for (int i = 0; i < 3; i++) {
alloc.destroy(p + i);
}
alloc.deallocate(p, 3); // give the memory back
return 0;
}Output:
100 200 300 6. Advantages of the STL
- Reusability: well-tested, efficient data structures and algorithms are ready to use.
- Generic: templates make them work with any type, including user-defined classes.
- Efficiency: each operation has a guaranteed complexity (e.g.
vector::push_backis amortised O(1),set::findis O(log n)). - Interchangeability: iterators let one algorithm work with many containers.
- Less code, fewer bugs: no hand-written linked lists or sorting loops.
Key points to remember
- STL = containers + algorithms + iterators (+ function objects and allocators); by Stepanov and Lee.
- Containers: sequence (
vector,deque,list), associative (set,multiset,map,multimap), adaptors (stack,queue,priority_queue). - Iterators act like pointers;
begin()is the first element,end()is one past the last. - Iterator categories: input, output, forward, bidirectional (
list,set,map), random access (vector,deque). - Allocators manage container memory; the default is
allocator<T>, which usesnewanddelete.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is the STL? Explain its components and how they work together. (10 Marks)
- Write: the definition and history, the components table, the diagram (algorithms → iterators → containers), and the headers table.
- Q2. Classify the STL containers. Explain each with its characteristics. (10 Marks)
- Write: the three categories, the standard containers table, and the "choosing a container" table.
- Q3. What are iterators? Explain the iterator categories. (5 Marks)
- Write: the definition,
begin()/end()and half-open ranges, the categories table, and the iterator loop program. - Q4. What are allocators? Why are they used? (2.5 Marks)
- Q5. Give the advantages of the STL. (2.5 Marks)