Chapter 14 Introduction to the Standard Template Library
§14.1 Introduction
§14.2 Containers
§14.3 Iterators
§14.4 Algorithms
§14.5 Function Objects
§14.1 Introduction
Standard Template Library (STL) 标准模板库 A software library included in the C++ Standard Library
Purpose To standardize commonly used components
History Originally developed by Alexander Stepanov in 1980s Accepted as part of C++ standard in Feb. 1994
2
Components of STL
Containers(容器) A container object, such as vector, used to store a
collection of data, often referred to as elements Algorithms(算法)
Functions to manipulate data such as sorting, searching, and comparing elements.
Most of them use iterators to access the elements in the container.
Iterators(迭代器) Objects that facilitate traversing through the elements in
a container Like built-in pointers that provide a convenient way to
access and manipulate the elements in a container
3
Components of STL
4
Algorithm 3Algorithm 3
Algorithm 2Algorithm 2Algorithm 1Algorithm 1
Container
Object 1 Object 2
Object 3
Iterator 3
Iterator 2Iterator 1
§14.2 Containers
5
ContainersContainers
•vector•deque•list
Sequence containers
•set•multiset•map•multimap
Associative containers
• stack• queue• priority_queue
Derived containers
linear data structures
Non-linear (tree) containers Suitable for searching
Constrained versions of sequence containers
Sequence Containers
Represent linear data structures Three sequence containers
vector 向量 , list 表 , and deque 双端队列 Differ only in performance
6
Element 0Element 0
iterator
Begin() end()
Element 1Element 1 Element 2Element 2Last
ElementLast
Element
int values[] = {1, 2, 3, 4 }; list<int> intList(values, values + 4);
Sequence Containers
7
Container Random access
Insertion or deletion in the
middle
Insertion or deletion at the
ends
vector Fast Slow Fast at back
list Slow Fast Fast at front
deque Fast SlowFast at both the ends
Associative Containers
Represent non-linear data structures (tree) Elements are sorted by keys
E.g. the name of student objects Suitable for searching via keys Set/Multiset: set of items Map/Multimap: set of item pairs
8
int values[] = {3, 5, 1, 7, 2, 2}; set<int> set1(values, values + 6);
map<int, string> map1; map1.insert(map<int, string>::value_type(100, "John Smith"));
Derived Containers
Containers adapted from the sequence containers For handling special cases
Programmer can choose an appropriate sequence container for a derived containers
9
Headerfile
Features Impl. struct.
stack <stack> Last-In-First-Out deque*, list, vector
queue <queue> First-In-First-Out deque*, list
priority_queue <queue> Largest-In-First-Out vector*, deque
*: default one
stack<int, vector<int> > stack2;
Containers supported by the STL
Container Description Header File
Iterator
vector A dynamic array. Allows insertions and deletion at back. Permits direct access to any element
<vector> Random access
list A bidirectional, linear list. Allows insertions and deletions anywhere.
<list> Bidirectional
deque A double-ended queue. Allows insertions and deletions at both the ends. Permits direct access to any element.
<deque> Random access
set An associate container for storing unique sets. Allows rapid lookup. (No duplicates allowed)
<set> Bidirectional
multiset An associate container for sorting non-unique sets. (Duplicates allowed)
<set> Bidirectional
10
Containers supported by the STL
Container Description Header File
Iterator
map An associate container for storing unique key/value pairs. Each key is associated with only one value (One-to-one mapping). Allows key-based lookup.
<map> Bidirectional
multimap An associate container for storing key/value pairs with one key may be associated with more than one value (one-to-many mapping). Allows key-based lookup.
<map> Bidirectional
stack A standard stack. Last-in-first-out(LIFO). <stack> No iterator
queue A standard queue. First-in-first-out(FIFO). <queue> No iterator
priority-queue
A priority queue. The first element out is always the highest priority element.
<queue> No iterator
11
Common Functions in All Containers
12
Functions Description
non-arg constructor Constructs an empty container.
constructor with args In addition to the non-arg constructor, every container
has several constructors with args.
copy constructor Creates a container by copying the elements from an
existing container of the same type.
destructor Performs cleanup after the container is destroyed.
empty() Returns true if there are no elements in the container.
size() Returns the number of elements in the container.
operator= Copies one container to another.
Relational operators The elements in the two containers are compared
(<, <=, >, >=, sequentially to determine the relation.
==, and !=)
Common Functions in Sequence/Associative Containers
13
Functions Description
c1.swap(c2) Swap the elements of two containers c1 and c2.
c.max_size() Returns the maximum number of elements a container can hold.
c.clear() Erases all the elements from the container.
c.begin() Returns an iterator to the first element in the container.
c.end() Returns an iterator that refers to the next position after the
end of the container.
c.rbegin() Returns an iterator to the last element in the container for
processing the elements in reverse order.
c.rend() Returns an iterator that refers to the position before the
first element in the container
c.erase(beg, end) Erases the elements in the container from beg to end-1. Bothe
beg and end are iterators.
Common Functions in Sequence Container
14
Functions Description
assign(n, elem) Assign n copies of the specified element in the container.
assign(beg, end) Assign the elements in the range from iterator
beg to iterator end.
push_back(elem) Appends an element in the container.
pop_back() Removes the last element from the container.
front() Returns the reference of the first element.
back() Returns the reference of the last element.
insert(position, elem) Inserts an element at the specified iterator.
Common Functions in Associative Containers
15
Functions Description
find(key) Returns an iterator that points to the element with
the specified key in the container.
lower_bound(key) Returns an iterator that points to the first
element with the specified key in the container.
upper_bound(key) Returns an iterator that points to the next element
after the last element with the specified key in
the container.
count(key) Returns the number of occurrences of the element
with the specified key in the container.
§14.3 Iterators
Iterators are objects to facilitate traversing through the elements in a container
A iterator is like a built-in pointer that can manipulate the elements in a container
16
random access
bidirectional
forward
input output
Iterators and Characteristics
Iterator Access method
Direction of movement
I/O capability Remark
Input Linear Forward only Read only Cannot be saved
Output Linear Forward only Write only Cannot be saved
Forward Linear Forward only Read/Write Can be saved
Bidirectional Linear Forward and backward
Read/Write Can be saved
Random Random Forward and backward
Read/Write Can be saved
17
Iterator Operations
Iterator Element access
Read Write Increment operation
Comparison
Input -> V=*p ++ ==,!=
Output V=*p *p=v ++ ==,!=
Forward -> V=*p *p=v ++ ==,!=
Bidirectional -> V=*p *p=v ++,-- ==,!=
Random ->,[] V=*p *p=v ++, --, _, -, +=, -=
==,!=,<,>,<=,>=
18
Iterator Types Supported by Containers
19
STL Container Type of Iterators Supported
vector random access iterators deque random access iterators
list bidirectional iterators
set bidirectional iterators
multiset bidirectional iterators
map bidirectional iterators
multimap bidirectional iterators
stack no iterator support
queue no iterator support
priority_queue no iterator support
Iterator Demo
20
vector<int> intVector; intVector.push_back(10); intVector.push_back(20); intVector.push_back(30); intVector.push_back(40); intVector.push_back(50); intVector.push_back(60);
vector<int>::iterator p1 = intVector.begin(); for (; p1 != intVector.end(); p1++){ cout << *p1 << " "; } cout << endl << *(--p1) << endl; cout << *(p1 - 3) << endl; cout << p1[-3] << endl; *p1 = 1234; cout << *p1 << endl;
IteratorDemoIteratorDemo Run
§14.4 Algorithms
More than sixty algorithms in STL Five groups
Retrieve or non-mutating Algorithms Mutating Algorithms Sorting Algorithms Set Algorithms Relational Algorithms
21
The copy Algorithm
22
template <typename InputIterator, typename OutputIterator>copy(InputIterator beg, InputIterator end, OutputIterator targetPostition)
int values[] = {1,2,3,4,5,6};vector<int> intVector(5);list<int> intList(5);
copy(values+2, values+4, intVector.begin());copy(values, values+5, intList.begin());
#include <algorithm>#include <vector>#include <list>#include <iterator>
Copy to Output Stream
23
intVector.insert(intVector.begin(), 747);
ostream_iterator<int> output(cout, " ");
cout<<"\nAfter the insertion funciton, intVector: ";copy(intVector.begin(), intVector.end(), output);
The copy Demo
24
After initial copy intVector: 3 4 0 0 0After initial copy intList: 1 2 3 4 5After the insertion function, intVector: 747 3 4 0 0 0After the copy function, intList: 747 3 4 0 5
int values[] = {1,2,3,4,5,6};vector<int> intVector(5);list<int> intList(5);
copy(values+2, values+4, intVector.begin());copy(values, values+5, intList.begin());intVector.insert(intVector.begin(), 747);copy(intVector.begin(), intVector.begin()+4, intList.begin());
int values[] = {1,2,3,4,5}vector<int> intVector;copy(values+2, values+4, intVector.begin());
Caution
The target container in copying must contains enough elements to store the values from the source container
25
“sort” and “binary_search”
26
template <typename RandomAccessIterator>void sort(RandomAccessIterator beg, RandomAccessIterator end)
template <typename RandomAccessIterator, typename relationalOperator>void sort(RandomAccessIterator beg, RandomAccessIterator end, relationalOperator op)
template <typename ForwardIterator, typename T>bool binary_search(ForwardIterator beg, ForwardIterator end, const T &value)
template <typename ForwardIterator, typename T, typename strickWeakOrdering>
bool binary_search(ForwardIterator beg, ForwardIterator end, const T &value, strickWeakOrdering op)
SortDemoSortDemo Run
Demo of sort, binary_search
27
int array1[] = {1, 7, 3, 4, 3, 3, 1, 2};
sort(array1, array1 + 8);
binary_search(array1, array1 + 8, 4)
sort(array1, array1 + 8, greater_equal<int>());
binary_search(array1, array1 + 8, 4, greater_equal<int>())
A function operator!A function operator!
§14.5 Function Objects Object can be used as a function
“function” “object” Passing a function as a parameter In <functional> header
28
int main(){int x[] = {10,50,30,40,20};int y[] = {70,90,60,80};sort(x,x+5,greater<int>());sort(y,y+4);for (int i=0;i<5;i++) cout<<x[i]<<" "; cout<<"\
n";for (int j=0;j<4;j++) cout<<y[j]<<" "; cout<<"\
n";int z[9];merge(x,x+5,y,y+4,z);for (int i=0;i<9;i++) cout<<z[i]<<" "; cout<<"\n";
}
Functors in <functional>
29
STL function object type STL function object type
equal_to<T> relational
not_equal_to<T> relational
greater<T> relational
greater_equal<T> relational
less<T> relational
less_equal<T> relational
logical_and<T> logical
logical_not<T> logical
logical_or<T> logical
plus<T> arithmetic
minus<T> arithmetic
multiplies<T> arithmetic
divides<T> arithmetic
modulus<T> arithmetic
negate<T> arithmetic
Customized Function Objects By defining member function operator() in a class
30
class My { public: int operator()(int a) {return a;} } ;My mo; int x = mo(0); template <typename T> class greater : binary_function <T,T,bool> {public: bool operator() (const T& x, const T& y) const{return x>y;}};
class BiggerThan{public: const int testValue; BiggerThan(int x) : testValue(x) { } bool operator()(int val) const { return val > testValue; }};
int my[] = {1, 7, 3, 4, 3, 3, 1, 2};sort(my, my + 8, Mygreater<int>());BiggerThan bt(10);cout<<bt(11)<<" "<<bt(9)<<endl;My m;cout<<m(4)<<endl;
1 04
A Summary
Concepts STL, Container, Iterator, Algorithm Three types of containers Function, Operation, Algorithm Functional object
Features of different containers Main functions of containers Features of STL algorithm Use of functional object
31
Top Related