Lesson 38 +40 XP

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.

ComponentWhat it isExamples
Containersobjects that store data (class templates)vector, list, deque, set, map, stack
Algorithmsprocedures that process the data in containers (function templates)sort, find, count, copy, reverse
Iteratorsobjects that point to elements, like pointers, and connect algorithms to containersvector<int>::iterator, list<string>::iterator
Function objectsobjects that act like functions, used to customise algorithmsless<int>, greater<int>, user functors
Allocatorsobjects that manage memory for containersallocator<T> (the default)

Algorithms reach container elements through iteratorsAlgorithms 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

HeaderContents
<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>.

CategoryContainersOrganisationTypical use
Sequence containersvector, deque, listelements kept in a linear order decided by where they were insertedlists of items in a given order
Associative containersset, multiset, map, multimapelements kept sorted by key (in a balanced tree) for fast searchlookup by key, unique collections
Derived containers (adaptors)stack, queue, priority_queuebuilt on top of a sequence container with a restricted interfaceLIFO, FIFO, highest-priority-first

The standard containers at a glance

ContainerHeaderStructureIteratorNotes
vector<vector>dynamic arrayrandom accessfast insert/delete at the back; [] indexing
deque<deque>double-ended queuerandom accessfast insert/delete at both ends
list<list>doubly linked listbidirectionalfast insert/delete anywhere; no []
set<set>sorted unique keysbidirectionalfast lookup; no duplicates
multiset<set>sorted keys, duplicates allowedbidirectional
map<map>sorted key → value pairs, unique keysbidirectionalm[key] access
multimap<map>key → value, duplicate keys allowedbidirectional
stack<stack>LIFO on a deque (default)nonepush, pop, top
queue<queue>FIFO on a deque (default)nonepush, pop, front, back
priority_queue<queue>heap on a vector (default)nonetop is always the largest

Members common to all containers

MemberMeaning
default, copy constructors; destructorcreate, 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 endvector
adding/removing at both endsdeque
frequent insertion/deletion in the middlelist
unique, sorted values; fast "is it there?"set
lookup of a value by a keymap
LIFO / FIFO / priority behaviourstack / 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().

C++
#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:

OUTPUT
vector: 10 20 30 40 50
v[2] is now 99
list backwards: c b a
first via const_iterator: 10

Iterator 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).

CategoryCan doProvided by
Inputread forward once (*it, ++)istream_iterator
Outputwrite forward onceostream_iterator, back_inserter
Forwardread and write, forward, multiple passes(hash containers in later standards)
Bidirectionalforward and backward ( - )list, set, map, multiset, multimap
Random accessjump 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 categoriesThe five iterator categories

Stream iterators

Iterators can also be attached to streams, which lets algorithms read from cin or print to cout:

C++
#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:

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>:

C++
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 memberTask
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)
C++
#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:

OUTPUT
100 200 300 

6. Advantages of the STL

  1. Reusability: well-tested, efficient data structures and algorithms are ready to use.
  2. Generic: templates make them work with any type, including user-defined classes.
  3. Efficiency: each operation has a guaranteed complexity (e.g. vector::push_back is amortised O(1), set::find is O(log n)).
  4. Interchangeability: iterators let one algorithm work with many containers.
  5. Less code, fewer bugs: no hand-written linked lists or sorting loops.
💡 Tip

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 uses new and delete.
🎯 END-TERM EXAM PREP

📝 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)