C++ Programming: Program Design Including Data Structures

Download Report

Transcript C++ Programming: Program Design Including Data Structures

C++ Programming:
Program Design Including
Data Structures, Fifth Edition
Chapter 22:
Standard Template Library (STL)
Objectives
In this chapter, you will:
• Learn about the Standard Template Library
(STL)
• Become familiar with the basic
components of the STL: containers,
iterators, and algorithms
• Explore how various containers are used
to manipulate data in a program
• Discover the use of iterators
• Learn about various generic algorithms
C++ Programming: Program Design Including Data Structures, Fifth Edition
2
Introduction
• ANSI/ISO Standard C++ is equipped with
a Standard Template Library (STL)
• The STL provides class templates to
process lists, stacks, and queues
• This chapter:
– Discusses many important features of the STL
– Shows how to use its tools
C++ Programming: Program Design Including Data Structures, Fifth Edition
3
Components of the STL
• Components of the STL:
– Containers
– Iterators
– Algorithms
• Containers and iterators are class
templates
• Iterators are used to step through the
elements of a container
• Algorithms are used to manipulate data
C++ Programming: Program Design Including Data Structures, Fifth Edition
4
Container Types
• Manage objects of a given type
• Three categories:
– Sequence (sequential) containers
– Associative containers
– Container adapters
C++ Programming: Program Design Including Data Structures, Fifth Edition
5
Sequence Containers
• Every object has a specific position
• Three predefined sequence containers:
– vector
– deque
– list
C++ Programming: Program Design Including Data Structures, Fifth Edition
6
Sequence Container: vector
• Stores and manages its objects in a
dynamic array
• Must have: #include <vector>
• To define an object of type vector,
specify the type of the object
– Examples:
vector<int> intList;
vector<string> stringList;
• vector contains several constructors
C++ Programming: Program Design Including Data Structures, Fifth Edition
7
Sequence Container: vector
(cont'd.)
• Basic vector operations:
– Item insertion and deletion
– Stepping through the elements
C++ Programming: Program Design Including Data Structures, Fifth Edition
8
Sequence Container: vector
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
9
Sequence Container: vector
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
10
Sequence Container: vector
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
11
Declaring an Iterator to a Vector
Container
• A vector contains a typedef iterator
• For example, the statement
vector<int>::iterator intVecIter;
declares intVecIter to be an iterator
into a vector container of type int
• ++intVecIter
– Advances the iterator
• *intVecIter
– Returns element at current iterator position
C++ Programming: Program Design Including Data Structures, Fifth Edition
12
Containers and the Functions
begin and end
• Every container contains the member
function begin and end
– begin returns the position of the first element
– end returns the position of the last element
• Both functions have no parameters
C++ Programming: Program Design Including Data Structures, Fifth Edition
13
Member Functions Common to All
Containers
C++ Programming: Program Design Including Data Structures, Fifth Edition
14
Member Functions Common to All
Containers (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
15
Member Functions Common to All
Containers (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
16
Member Functions Common to
Sequence Containers
C++ Programming: Program Design Including Data Structures, Fifth Edition
17
Member Functions Common to
Sequence Containers (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
18
The copy Algorithm
• Function copy: convenient way to output the
elements of a container
• Copies elements from one place to another
– Can output the elements of a vector
• Prototype:
copies elements within range first1...last-1
• Must have: #include <algorithm>
C++ Programming: Program Design Including Data Structures, Fifth Edition
19
The copy Algorithm (cont'd.)
• Example:
int intArray[] = {5, 6, 8, 3, 40, 36, 98, 29, 75};
vector<int> vecList(9);
copy(intArray, intArray + 9, vecList.begin());
• After the previous statement executes:
vecList = {5, 6, 8, 3, 40, 36, 98, 29, 75}
C++ Programming: Program Design Including Data Structures, Fifth Edition
20
The copy Algorithm (cont'd.)
• Consider the statement :
copy(intArray + 1, intArray + 9, intArray);
• After the previous statement executes:
intArray = {6, 8, 3, 40, 36, 98, 29, 75, 75}
• Now, consider the statement:
copy(vecList.rbegin() + 2, vecList.rend(),
vecList.rbegin());
• After the previous statement executes:
vecList = {5, 6, 5, 6, 8, 3, 40, 36, 98}
C++ Programming: Program Design Including Data Structures, Fifth Edition
21
The ostream Iterator and the
Function copy
• One way to output the contents of a container
is to use a for loop, along with begin
(initialize) and end (loop limit)
• copy can output a container
– An iterator of the type ostream specifies
destination
• When creating an iterator of the type
ostream:
– Specify the type of element that the iterator will
output
C++ Programming: Program Design Including Data Structures, Fifth Edition
22
The ostream Iterator and the
Function copy (cont'd.)
• Example:
ostream_iterator<int> screen(cout, " ");
copy(intArray, intArray + 9, screen);
copy(vecList.begin(), vecList.end(), screen);
• The last statement is equivalent to:
copy(vecList.begin(), vecList.end(),
ostream_iterator<int>(cout, " "));
• Another example:
copy(vecList.begin(), vecList.end(),
ostream_iterator<int>(cout, ", "));
C++ Programming: Program Design Including Data Structures, Fifth Edition
23
Sequence Container: deque
• deque stands for double-ended queue
• Implemented as dynamic arrays
• Elements can be inserted at both ends
• A deque can expand in either direction
• Elements are also inserted in the middle
C++ Programming: Program Design Including Data Structures, Fifth Edition
24
Sequence Container: deque
(cont’d.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
25
Sequence Container: deque
(cont’d.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
26
Sequence Container: list
• Lists are implemented as doubly linked
lists
• Every element in a list points to both its
immediate predecessor and its immediate
successor
– Except the first and last element
• The list is not a random access data
structure
C++ Programming: Program Design Including Data Structures, Fifth Edition
27
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
28
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
29
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
30
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
31
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
32
Sequence Container: list
(cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
33
Iterators
• An iterator points to the elements of a
container (sequence or associative)
• Iterators provide access to each element
• Most common operations on iterators
– ++ (increment)
– * (dereference)
C++ Programming: Program Design Including Data Structures, Fifth Edition
34
Types of Iterators
• Input iterators: have read access; step
forward element-by-element
• Output iterators: have write access; step
forward element-by-element
• Forward iterators: have all functionality of
input and almost all of output iterators
• Bidirectional iterators: can go backward
• Random access iterators: bidirectional
iterators that can randomly process the
elements of a container
C++ Programming: Program Design Including Data Structures, Fifth Edition
35
Input Iterators
C++ Programming: Program Design Including Data Structures, Fifth Edition
36
Output Iterators
• Output iterators cannot be used to iterate
over a range twice
– If we write data at same position, there is no
guarantee that new value will replace old one
C++ Programming: Program Design Including Data Structures, Fifth Edition
37
Forward Iterators
C++ Programming: Program Design Including Data Structures, Fifth Edition
38
Bidirectional Iterators
• Forward iterators that can also iterate
backward over the elements
– The operations defined for forward iterators
apply to bidirectional iterators
• Use the decrement operator to step
backward
C++ Programming: Program Design Including Data Structures, Fifth Edition
39
Random Access Iterators
• Can be used with containers of the types
vector, deque, string, as well as arrays
• Operations defined for bidirectional
iterators apply to random access iterators
C++ Programming: Program Design Including Data Structures, Fifth Edition
40
Types of Iterators (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
41
typedef iterator
• Every container contains a typedef
iterator
• The statement:
vector<int>::iterator intVecIter;
declares intVecIter to be an iterator
into a vector container of the type int
C++ Programming: Program Design Including Data Structures, Fifth Edition
42
typedef const_iterator
• With the help of an iterator into a container
and the dereference operator, *, you can
modify the elements of the container
• If the container is declared const, then
we must prevent the iterator from
modifying the elements
• Every container contains typedef
const_iterator to handle these
situations
C++ Programming: Program Design Including Data Structures, Fifth Edition
43
typedef reverse_iterator
• Every container also contains the
typedef reverse_iterator
• An iterator of this type is used to iterate
through the elements of a container in
reverse
C++ Programming: Program Design Including Data Structures, Fifth Edition
44
typedef const_reverse_iterator
• Read-only iterator
• Used to iterate through the elements of a
container in reverse
• Required if:
– The container is declared as const
– Need to iterate through the elements of the
container in reverse
C++ Programming: Program Design Including Data Structures, Fifth Edition
45
Other typedefs Common to All
Containers
C++ Programming: Program Design Including Data Structures, Fifth Edition
46
Stream Iterators
• istream_iterator
– Used to input data into a program from an
input stream
• ostream_iterator
– Used to output data into an output stream
C++ Programming: Program Design Including Data Structures, Fifth Edition
47
Associative Containers
• Elements in an associative container are
automatically sorted according to some
ordering criteria
• Predefined associative containers in the
STL:
– Sets
– Multisets
– Maps
– Multimaps
C++ Programming: Program Design Including Data Structures, Fifth Edition
48
Associative Containers: set and
multiset
• Associative containers set and
multiset automatically sort their
elements
– multiset allows duplicates; set does not
• The default sorting criterion is the
relational operator < (less than)
– Ascending order
• Must #include <set>
C++ Programming: Program Design Including Data Structures, Fifth Edition
49
Declaring set or multiset
Associative Containers
C++ Programming: Program Design Including Data Structures, Fifth Edition
50
Declaring set or multiset
Associative Containers (cont'd.)
• To use sort criteria other than the default,
specify this option when declaring container:
• In the statements in Lines 2 and 4, note the
space between the two > symbols
– This space is important because >> is also a shift
operator in C++
C++ Programming: Program Design Including Data Structures, Fifth Edition
51
Item Insertion and Deletion from
set/multiset
C++ Programming: Program Design Including Data Structures, Fifth Edition
52
Item Insertion and Deletion from
set/multiset (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
53
Container Adapters
• Containers to accommodate special
situations
• The three container adapters are:
– Stacks
– Queues
– Priority Queues
• Do not support any type of iterator
C++ Programming: Program Design Including Data Structures, Fifth Edition
54
Stack
• The STL provides a stack class
C++ Programming: Program Design Including Data Structures, Fifth Edition
55
Queue
C++ Programming: Program Design Including Data Structures, Fifth Edition
56
Containers, Associated Header
Files, and Iterator Support
• Every container is a class
• Definition of the class implementing a
specific container is contained in the
header file
• Table 22-21
– Describes the container, its associated header
file, and the type of iterator supported by the
container
C++ Programming: Program Design Including Data Structures, Fifth Edition
57
Algorithms
• Several operations can be defined for a
container
– Some operations very specific to a container
are provided as part of the container definition
– Other operations are common to all
containers
• Generic algorithms contained in the
header file algorithm
C++ Programming: Program Design Including Data Structures, Fifth Edition
58
STL Algorithm Classification
• Operations such as find, sort, and
merge are common to all containers
– Provided as generic algorithms
• STL algorithms classifications:
– Nonmodifying algorithms
– Modifying algorithms
– Numeric algorithms
– Heap algorithms
C++ Programming: Program Design Including Data Structures, Fifth Edition
59
Nonmodifying Algorithms
• Do not modify the elements of the
container
C++ Programming: Program Design Including Data Structures, Fifth Edition
60
Numeric Algorithms
• Perform numeric calculations on the
elements of a container
C++ Programming: Program Design Including Data Structures, Fifth Edition
61
Heap Algorithms
• Heap sort algorithm sorts array data
• The array containing the data is viewed as
a binary tree
C++ Programming: Program Design Including Data Structures, Fifth Edition
62
Function Objects
• To make a generic algorithm flexible, the
STL usually provides two forms:
– Use the natural operation to accomplish the
goal
– Specify criteria based on which algorithm
processes the elements
• Example: adjacent_find searches and
returns position of first two equal elements
– Alternatively, we can specify criteria (say, less
than) to look for the first two elements
C++ Programming: Program Design Including Data Structures, Fifth Edition
63
Function Objects (cont'd.)
• Function object: contains a function that
can be treated as such using the
operator()
– Class template that overloads the function call
operator
• STL provides arithmetic, relational, and
logical function objects
– Contained in the header file functional
• Can also create your own
C++ Programming: Program Design Including Data Structures, Fifth Edition
64
Function Objects (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
65
Function Objects (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
66
Function Objects (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
67
Function Objects (cont'd.)
• The STL relational function objects can
also be applied to containers
• Example:
vecList = {2, 3, 4, 5, 1, 7, 8, 9};
• To see if the elements are out of order:
intItr = adjacent_find(vecList.begin(),
vecList.end(), greater<int>());
The function returns a pointer to element 5, which is
stored in intItr
C++ Programming: Program Design Including Data Structures, Fifth Edition
68
Function Objects (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
69
Predicates
• Special types of function objects that
return Boolean values
– Typical use: specify searching/sorting criteria
• Two types:
– Unary: check a property for a single argument
– Binary: check a specific property for a pair
• Predicate must always return the same
result for the same value
• Functions that modify their internal states
cannot be considered predicates
C++ Programming: Program Design Including Data Structures, Fifth Edition
70
Insert Iterator
• back_inserter: uses push_back in
place of = operator; the argument is the
container
copy(list, list + 5, back_inserter(vList));
• front_inserter: uses push_front;
argument is the container itself
– Cannot be used for the vector container
• inserter: uses insert
– Two arguments: the container and an iterator
to the container specifying the position at
which the insertion should begin
C++ Programming: Program Design Including Data Structures, Fifth Edition
71
STL Algorithms
• STL algorithms include documentation
with the function prototypes
• The parameter types indicate for which
type of container the algorithm is
applicable
C++ Programming: Program Design Including Data Structures, Fifth Edition
72
Fill Functions
• fill: fills a container with elements
• fill_n: fills in the next n elements
– The element that is used as a filling element
is passed as a parameter
• Defined in header file algorithm
• Prototypes:
C++ Programming: Program Design Including Data Structures, Fifth Edition
73
Generate Functions
• Used to generate elements and fill a
sequence
• Defined in header file algorithm
• Prototypes:
C++ Programming: Program Design Including Data Structures, Fifth Edition
74
Find Functions
C++ Programming: Program Design Including Data Structures, Fifth Edition
75
Remove Functions
• remove: removes certain elements from a
sequence
• remove_if: removes elements from a
sequence by using some criteria
C++ Programming: Program Design Including Data Structures, Fifth Edition
76
Replace and Copy Functions
• Replace specified values
C++ Programming: Program Design Including Data Structures, Fifth Edition
77
Swap Functions
• Swaps elements
• Defined in header file algorithm
• Prototypes:
C++ Programming: Program Design Including Data Structures, Fifth Edition
78
Search and Sort Functions
• Searches for and sorts elements
C++ Programming: Program Design Including Data Structures, Fifth Edition
79
Search and Sort Functions
(cont'd.)
• adjacent_find: finds the first
occurrence of consecutive elements that
meet criteria
C++ Programming: Program Design Including Data Structures, Fifth Edition
80
Merge Functions
• merge: merges the sorted lists
– The lists must be sorted using same criteria
C++ Programming: Program Design Including Data Structures, Fifth Edition
81
Merge Functions (cont'd.)
• inplace_merge: combines sorted
sequences
C++ Programming: Program Design Including Data Structures, Fifth Edition
82
Reverse and Rotate Functions
• reverse: reverses the order of the
elements in a given range
• reverse_copy: reverses the elements of a
given range while copying into a destination
range; the source is not modified
• rotate: rotates the elements of a given
range
• rotate_copy: combination of rotate and
copy elements of the source are copied at
the destination in a rotated order
– The source is not modified
C++ Programming: Program Design Including Data Structures, Fifth Edition
83
Reverse and Rotate Functions
(cont’d.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
84
Count Functions
• count: counts the occurrence of a
given item in a given range; returns the
number of times the value specified by
the parameter occurs
• count_if: counts occurrences of a
given value in a given range satisfying
a certain criterion
C++ Programming: Program Design Including Data Structures, Fifth Edition
85
Max/Min Functions
• min: determines the minimum of two
values
• max: determines the maximum of two
values
• max_element: determines the largest
element in a given range
• min_element: determines the
smallest element in a given range
C++ Programming: Program Design Including Data Structures, Fifth Edition
86
Shuffle Functions
• random_shuffle: randomly orders
elements
C++ Programming: Program Design Including Data Structures, Fifth Edition
87
for_each Function
• for_each: accesses and processes each
element in a given range by applying a
function
• Prototype:
C++ Programming: Program Design Including Data Structures, Fifth Edition
88
transform Function
• transform: creates a sequence of
elements at the destination by applying the
unary operation to each element in the
range
C++ Programming: Program Design Including Data Structures, Fifth Edition
89
Set Functions
C++ Programming: Program Design Including Data Structures, Fifth Edition
90
Numeric Functions
C++ Programming: Program Design Including Data Structures, Fifth Edition
91
Numeric Functions (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition
92
Summary
• STL consists of:
– Containers: class templates
– Iterators: step through the elements of a
container
– Algorithms: manipulate the elements in a
container
C++ Programming: Program Design Including Data Structures, Fifth Edition
93
Summary (cont'd.)
• Containers
– Sequence: vector, deque, and list
– Associative: sets, multisets, maps, and
multimaps
– Container adapters: stacks, queues, and
priority queues
C++ Programming: Program Design Including Data Structures, Fifth Edition
94
Summary (cont'd.)
• Iterators: input, output, forward,
bidirectional, and random access iterator
• Predicates: Boolean function objects
• Algorithms: nonmodifying, modifying,
numerical, and heap
– Algorithms are overloaded for flexibility
C++ Programming: Program Design Including Data Structures, Fifth Edition
95