CPSC 427a: Object-Oriented Programming
Michael J. Fischer
The C++ Standard Library (cont.)
Iterators
Iterators are like generalized pointers into containers.
Most pointer operations *, ->, ++, ==, !=, etc. work with iterators.
Iterator example
Here’s a program to store and print the first 10 perfect squares.
Using iterator inside a class
Using subscripts and size()
Algorithms
STL has algorithms as well as data structures.
You must #include <algorithm>.
Commonly used: copy, fill, swap, max, min, max_element,
min_element, but there are many many more.
We’ll look at sort in greater detail.
STL sort algorithm
sort works only on randomly-accessible containers such as vector.
(list has its own sort method.)
sort takes two iterator arguments to designate the sort range.
It can also take an optional third “comparison” argument to define the
sort order.
Reverse sort example
Reverse sort example (cont.)
pair<T1, T2>
A pair<T1, T2> is an ordered pair of elements of type T1 and T2, respectively.
Class pair<T1, T2> has public data members first and second.
Example:
map<Key,Val>
map<Key,Val> associates a value with each key.
More precisely, it is an ordered collection of elements of type
pair<Key,Val>.
You must #include <map>.
Can use standard subscript notation to access map contents, where
subscript is the key.
Can also use a map iterator, which returns a pointer to a pair.
Using a map<Key,Val>
Example:
Copying from one container to another
Two ways to copy multiple elements in one statement.
Suppose m is a map and v a vector of pairs compatible with m.
Copying from one container to another – example
A map can be copied into a vector of pairs.
string class
The standard string class tries to make strings behave like other built-in data types.
Like vector<char>, strings are growable, but they are not implemented using vector, and they support many special string operations.
They can be assigned (=, assign()), compared (==, !=, <, <=, >, >=, compare()), concatenated (+), read and written (>>, <<), searched (find(), …), extracted ([], substr()), modified (+=, append(), …), and more.
Their length can be found (size(), length()).
s.c_str() returns a copy of s as a C string.
You must #include <string>.