Home | Projects | Notes > C++ Programming > Introduction to Standard Template Library
A library of powerful, reusable, adaptable, generic classes and functions.
Implemented using C++ templates.
Implements common data structures and algorithms.
Huge class library!
Developed by Alexander Stepanov (1994).
Reference: cppreference.com
Assortment of commonly used containers.
Known time and size complexity.
Tried and tested - Reusability!
Consistent, fast, and type-safe.
Extensible
Containers - Collections of objects or primitive types (array, vector, deque, stack, set, map, etc.)
Algorithms - Functions for processing sequences of elements from containers (find, max, count, accumulate, sort, etc.) The STL has about 60 algorithms that can be used and extended to work with any type of data.
Iterators - Generate sequences of element from containers (forward, reverse, by value, by reference, constant, etc.)
281
2
3// std::sort, std::reverse
4// std::accumulate
5
6int main(int argc, char *argv[])
7{
8 std::vector<int> v {1, 5, 3};
9
10 // Sort a vector
11 std::sort(v.begin(), v.end());
12 for (auto elem : v)
13 std::cout << elem << " ";
14 std::cout << std::endl;
15
16 // Reverse a vector
17 std::reverse(v.begin(), v.end());
18 for (auto elem : v)
19 std::cout << elem << " ";
20 std::cout << std::endl;
21
22 // Accumulate
23 int sum{};
24 sum = std::accumulate(v.begin(), v.end(), 0); // 3rd param: initial running sum
25 std::cout << sum << std::endl;
26
27 return 0;
28}
311 3 5
25 3 1
39
Sequence containers - array, vector, list, forward_list, deque
Maintains the ordering of the inserted elements.
Associative containers - set, multiset, map, multimap
Inserts elements in a pre-defined order, or no order at all.
Container adapters - stack, queue, priority queue
Wrappers around existing containers that provide a different interface. Not standalone container implementations but instead reuse existing containers (such as deque
or vector
) under the hood while exposing a modified API.
Does not support iterators, can't be used with STL algorithms.
Input iterators - From the container to the program.
Output iterators - From the program to the container.
Forward iterators - Navigate one item at a time in one direction.
Bi-directional iterators - Navigate one item at a time both directions.
Random access iterators - Directly access a container item. (Can use the subscript operator to directly access elements.)
There are about 60 algorithms in the STL. Depending on whether an algorithm modifies the sequence it operates on, they can be classified into two groups:
Non-modifying
Modifying