Standard Template Library - Containers & Iterators
Standard Template Library
Each template consists of three main parts:
- Containers - Standard data structures.
- Iterators - Standard ways to move through the standard data structures.
- Algorithms - Use iterators to complete a task with data.
Containers
An example of a container is a vector
this is how you would initialise a vector
:
#include <vector>
using namespace std;
int main() {
vector<int> store;
}
A vector is an automatically sizing array.
You can use the algorithms of a container using dot noation: store.back()
.
Iterators
Iterators point to an object in an array, or container. They can iterate through the objects in a logical way, by using overloaded operators such as ++
.
See https://www.cplusplus.com/reference/iterator/ for the properties of each iterator category. We can use the functions at the bottom of the page to control the iterator.
If a type is well-defined then we can replace the standard iterator declaration:
multiset<int>::iterator it = store.begin();
with either of the following:
auto it = store.begin();
for (int x : store) {
cout << x;
}
for (auto x : store) {
cout << x;
}
STL Arrays
There is also an array
container, in C++, that enable the use of iterators and algorithms:
#include <array>
#include <iostream>
using namespace std;
int main() {
array<long, 5> arr;
arr.fill(1); // all elements are 1
for (auto x : arr) {
cout << x;
}
}