Transcript CppHTP6e_22

1
22
Standard Template
Library (STL)
 2008 Pearson Education, Inc. All rights reserved.
2
The shapes a bright container can contain!
— Theodore Roethke
Journey over all the universe in a map.
— Miguel de Cervantes
O! thou hast damnable iteration, and art indeed able to
corrupt a saint.
— William Shakespeare
That great dust heap called “history.”
— Augustine Birrell
The historian is a prophet in reverse.
— Friedrich von Schlegel
Attempt the end, and never stand to doubt; Nothing's so
hard but search will find it out.
— Robert Herrick
 2008 Pearson Education, Inc. All rights reserved.
3
OBJECTIVES
In this chapter you will learn:
 To be able to use the template STL
containers, container adapters and "near
containers."
 To be able to program with the dozens of STL
algorithms.
 To understand how algorithms use iterators to
access the elements of STL containers.
 To become familiar with the STL resources
available on the Internet and the World Wide
Web.
 2008 Pearson Education, Inc. All rights reserved.
4
22.1
22.2
22.3
22.4
Introduction to the Standard Template Library (STL)
22.1.1
Introduction to Containers
22.1.2
Introduction to Iterators
22.1.3
Introduction to Algorithms
Sequence Containers
22.2.1
vector Sequence Container
22.2.2
list Sequence Container
22.2.3
deque Sequence Container
Associative Containers
22.3.1
multiset Associative Container
22.3.2
set Associative Container
22.3.3
multimap Associative Container
22.3.4
map Associative Container
Container Adapters
22.4.1
stack Adapter
22.4.2
queue Adapter
22.4.3
priority_queue Adapter
 2008 Pearson Education, Inc. All rights reserved.
5
22.5
Algorithms
22.5.1
fill, fill_n, generate and generate_n
22.5.2
equal, mismatch and lexicographical_compare
22.5.3
remove, remove_if, remove_copy and
remove_copy_if
22.5.4
22.5.5
22.5.6
22.5.7
22.5.8
22.5.9
22.5.10
22.5.11
22.5.12
22.5.13
22.5.14
replace, replace_if, replace_copy
and replace_copy_if
Mathematical Algorithms
Basic Searching and Sorting Algorithms
swap, iter_swap and swap_ranges
copy_backward, merge, unique and reverse
inplace_merge, unique_copy and reverse_copy
Set Operations
lower_bound, upper_bound and equal_range
Heapsort
min and max
STL Algorithms Not Covered in This Chapter
 2008 Pearson Education, Inc. All rights reserved.
6
22.6
Class bitset
22.7
Function Objects
22.8
Wrap-Up
22.9
STL Internet and Web Resources
 2008 Pearson Education, Inc. All rights reserved.
22.1 Introduction to the Standard
Template Library (STL)
7
• Standard Template Library (STL)
– Defines powerful, template-based, reusable components
and algorithms to process them
• Implement many common data structures
– Developed by Alexander Stepanov and Meng Lee
– Conceived and designed for performance and flexibility
– Three key components
• Containers
• Iterators
• Algorithms
 2008 Pearson Education, Inc. All rights reserved.
8
Performance Tip 22.1
For any particular application, several different
STL containers might be appropriate. Select the
most appropriate container that achieves the best
performance (i.e., balance of speed and size) for
that application. Efficiency was a crucial
consideration in STL’s design.
 2008 Pearson Education, Inc. All rights reserved.
9
Performance Tip 22.2
Standard Library capabilities are implemented to
operate efficiently across many applications. For
some applications with unique performance
requirements, it might be necessary to write your
own customized implementations.
 2008 Pearson Education, Inc. All rights reserved.
22.1 Introduction to the Standard
Template Library (STL) (Cont.)
10
• STL containers
– Three container categories
• First-class containers
• Adapters
• Near containers
– Each container has associated member functions
• Some member functions are defined in all STL containers
 2008 Pearson Education, Inc. All rights reserved.
22.1 Introduction to the Standard
Template Library (STL) (Cont.)
11
• STL iterators
– Used to manipulate STL-container elements
• Have properties similar to those of pointers
– Standard pointers can be used as iterators
• So standard arrays can be manipulated as STL containers
 2008 Pearson Education, Inc. All rights reserved.
22.1 Introduction to the Standard
Template Library (STL) (Cont.)
12
• STL algorithms
– Perform common data manipulations such as searching,
sorting and comparing
– Mostly use iterators to access container elements
• Each algorithm has minimum iterator requirements
– Can be used on any container whose supported iterator
type satisfies those requirements
 2008 Pearson Education, Inc. All rights reserved.
13
Software Engineering Observation 22.1
The STL approach allows general programs to be
written so that the code does not depend on the
underlying container. Such a programming style
is called generic programming.
 2008 Pearson Education, Inc. All rights reserved.
14
Software Engineering Observation 22.2
Avoid reinventing the wheel; program with the
reusable components of the C++ Standard
Library. STL includes many of the most popular
data structures as containers and provides
various popular algorithms to process data in
these containers.
 2008 Pearson Education, Inc. All rights reserved.
15
Error-Prevention Tip 22.1
When programming pointer-based data structures and
algorithms, we must do our own debugging and testing to
be sure our data structures, classes and algorithms
function properly. It is easy to make errors when
manipulating pointers at this low level. Memory leaks and
memory-access violations are common in such custom
code. For most programmers, and for most of the
applications they will need to write, the prepackaged,
templatized containers of the STL are sufficient. Using the
STL helps programmers reduce testing and debugging
time. One caution is that, for large projects, template
compile time can be significant.
 2008 Pearson Education, Inc. All rights reserved.
16
22.1.1 Introduction to Containers
• STL containers
– Three major categories
• Sequence containers
– Represent linear data structures
• Associative containers
– Nonlinear containers
– Store key/value pairs
• Container adapters
– Implemented as constrained sequence containers
– “Near-containers”
• Pointer-based arrays, strings, bitsets and valarrays
 2008 Pearson Education, Inc. All rights reserved.
17
Standard Library
container class
Description
Sequence containers
Vector
rapid insertions and deletions at back
direct access to any element
rapid insertions and deletions at front or back
direct access to any element
doubly linked list, rapid insertion and deletion anywhere
deque
list
Associative containers
set
multiset
map
rapid lookup, no duplicates allowed
rapid lookup, duplicates allowed
one-to-one mapping, no duplicates allowed, rapid key-based
lookup
one-to-many mapping, duplicates allowed, rapid key-based
lookup
multimap
Container adapters
stack
queue
priority_queue
last-in, first-out (LIFO)
first-in, first-out (FIFO)
highest-priority element is always the first element out
Fig. 22.1 | Standard Library container classes.
 2008 Pearson Education, Inc. All rights reserved.
18
22.1.1 Introduction to Containers (Cont.)
• STL containers (Cont.)
– Common functions
• All STL containers provide similar functionality
• Many generic operations apply to all containers
• Others apply of subsets of similar containers
– Header files
• STL containers are found in various header files
• STL containers are all in namespace std
 2008 Pearson Education, Inc. All rights reserved.
19
Common member
functions for all STL
containers
default constructor
empty
Size
operator=
operator<
operator<=
operator>
operator>=
operator==
operator!=
swap
Description
A constructor to provide a default initialization of the
container. Normally, each container has several
constructors that provide different initialization methods for
the container.
Returns true if there are no elements in the container;
otherwise, returns false.
Returns the number of elements currently in the container.
Assigns one container to another.
Returns true if the first container is less than the second
container; otherwise, returns false.
Returns true if the first container is less than or equal to
the second container; otherwise, returns false.
Returns true if the first container is greater than the
second container; otherwise, returns false.
Returns true if the first container is greater than or equal
to the second container; otherwise, returns false.
Returns true if the first container is equal to the second
container; otherwise, returns false.
Returns true if the first container is not equal to the second
container; otherwise, returns false.
Swaps the elements of two containers.
Fig. 22.2 | STL container common functions. (Part 1 of 2)
 2008 Pearson Education, Inc. All rights reserved.
20
Common member
functions for all STL
containers
Description
Functions found only in first-class containers
max_size
begin
end
rbegin
rend
erase
clear
Returns the maximum number of elements for a container.
The two versions of this function return either an
iterator or a const_iterator that refers to the first
element of the container.
The two versions of this function return either an
iterator or a const_iterator that refers to the next
position after the end of the container.
The two versions of this function return either a
reverse_iterator or a const_reverse_iterator
that refers to the last element of the container.
The two versions of this function return either a
reverse_iterator or a const_reverse_iterator
that refers to the next position after the last element of the
reversed container.
Erases one or more elements from the container.
Erases all elements from the container.
Fig. 22.2 | STL container common functions. (Part 2 of 2)
 2008 Pearson Education, Inc. All rights reserved.
21
Standard Library container header files
<vector>
<list>
<deque>
<queue>
Contains both queue and priority_queue.
<stack>
<map>
Contains both map and multimap.
<set>
Contains both set and multiset.
<bitset>
Fig. 22.3 | Standard Library container header files.
 2008 Pearson Education, Inc. All rights reserved.
22
typedef
Description
value_type
Reference
The type of element stored in the container.
A reference to the type of element stored in the container.
const_reference
A constant reference to the type of element stored in the
container. Such a reference can be used only for reading
elements in the container and for performing const
operations.
A pointer to the type of element stored in the container.
An iterator that points to the type of element stored in the
container.
A constant iterator that points to the type of element
stored in the container and can be used only to read
elements.
pointer
iterator
const_iterator
Fig. 22.4 | typedefs found in first-class containers. (part 1 of 2)
 2008 Pearson Education, Inc. All rights reserved.
23
typedef
Description
reverse_iterator
A reverse iterator that points to the type of element
stored in the container. This type of iterator is for
iterating through a container in reverse.
A constant reverse iterator that points to the type of
element stored in the container and can be used only to
read elements. This type of iterator is for iterating
through a container in reverse.
The type of the result of subtracting two iterators that
refer to the same container (operator - is not defined
for iterators of lists and associative containers).
The type used to count items in a container and index
through a sequence container (cannot index through a
list).
const_reverse_iterator
difference_type
size_type
Fig. 22.4 | typedefs found in first-class containers. (part 2 of 2)
 2008 Pearson Education, Inc. All rights reserved.
24
Performance Tip 22.3
STL generally avoids inheritance and virtual
functions in favor of using generic programming
with templates to achieve better execution-time
performance.
 2008 Pearson Education, Inc. All rights reserved.
25
Portability Tip 22.1
Programming with STL will enhance the
portability of your code.
 2008 Pearson Education, Inc. All rights reserved.
26
22.1.1 Introduction to Containers (Cont.)
• STL containers (Cont.)
– Type requirements for STL container elements
• Elements must be copied to be inserted in a container
– Element’s type must provide copy constructor and
assignment operator
• Compiler will provide default memberwise copy and
default memberwise assignment, which may or may
not be appropriate
• Elements might need to be compared
– Element’s type should provide equality operator and
less-than operator
 2008 Pearson Education, Inc. All rights reserved.
27
Software Engineering Observation 22.3
The STL containers technically do not require their
elements to be comparable with the equality and less-than
operators unless a program uses a container member
function that must compare the container elements (e.g.,
the sort function in class list). Unfortunately, some
prestandard C++ compilers are not capable of ignoring
parts of a template that are not used in a particular
program. On compilers with this problem, you may not be
able to use the STL containers with objects of classes that
do not define overloaded less-than and equality operators.
 2008 Pearson Education, Inc. All rights reserved.
28
22.1.2 Introduction to Iterators
• STL iterators
– Have many features in common with pointers
• Used to point to elements of first-class containers
• Dereferencing operator (*) accesses current element
• ++ operator moves iterator to next element of the container
– Hold state information for their particular containers
– First-class container member functions
• Member function begin
– Returns iterator pointing to first element
• Member function end
– Returns iterator pointing just past last element
 2008 Pearson Education, Inc. All rights reserved.
29
22.1.2 Introduction to Iterators (Cont.)
• STL iterators (Cont.)
– iterator versus const_iterator
• const_iterators cannot modify container elements
– Iterators are used with sequences (also called ranges)
• Sequences can be in containers
• Sequences can be input or output sequences
– istream_iterator
• An iterator for an input sequence
– ostream_iterator
• An iterator for an output sequence
 2008 Pearson Education, Inc. All rights reserved.
30
Error-Prevention Tip 22.2
The * (dereferencing) operator of any const
iterator returns a const reference to the
container element, disallowing the use of nonconst member functions.
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.5: Fig22_05.cpp
2
// Demonstrating input and output with iterators.
3
#include <iostream>
4
5
6
using std::cout;
using std::cin;
using std::endl;
31
Outline
7
8 #include <iterator> // ostream_iterator and istream_iterator
9
Create
10 int main()
11 {
12
13
14
// create istream_iterator for reading int values from cin
std::istream_iterator< int > inputInt( cin );
19
20
21
22
int number2 = *inputInt; // read int from standard input
23
24
25
26
(1 of 2)
an istream_iterator
capable of extracting int values
from standard input cin
cout << "Enter two integers: ";
15
16
17
18
Fig22_05.cpp
Dereference istream_iterator
inputInt to read an int from cin
int number1 = *inputInt; // read int from standard input
Position
++inputInt; // move iterator to next input value
// create ostream_iterator for writing int values to cout
std::ostream_iterator< int > outputInt( cout );
cout << "The sum is: ";
*outputInt = number1 + number2; // output result to cout
cout << endl;
27
return 0;
28 } // end main
istream_iterator inputInt
to the next value in the input stream
Create an ostream_iterator
capable of inserting int values
into standard output cout
Dereference outputInt and use it as
an lvalue to output an integer to cout
 2008 Pearson Education,
Inc. All rights reserved.
Enter two integers: 12 25
The sum is: 37
32
Outline
Fig22_05.cpp
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
33
Common Programming Error 22.1
Attempting to dereference an iterator positioned
outside its container is a runtime logic error. In
particular, the iterator returned by end cannot
be dereferenced or incremented.
 2008 Pearson Education, Inc. All rights reserved.
34
Common Programming Error 22.2
Attempting to create a non-const iterator
for a const container results in a
compilation error.
 2008 Pearson Education, Inc. All rights reserved.
35
22.1.2 Introduction to Iterators (Cont.)
• STL iterators (Cont.)
– Iterator categories
• Input – can move forward one position, can read elements
• Output – can move forward one position, can write elements
• Forward – can move forward one position, can read and
write elements
• Bidirectional – can move forward or backward one position,
can read and write elements
• Random access – can move forward or backward any
number of positions, can read and write elements
– Each category supports all functionality of categories
above it
– Iterator category determines what algorithms can be used
 2008 Pearson Education, Inc. All rights reserved.
36
Category
Description
input
Used to read an element from a container. An input iterator can move
only in the forward direction (i.e., from the beginning of the container
to the end) one element at a time. Input iterators support only one-pass
algorithms—the same input iterator cannot be used to pass through a
sequence twice.
Used to write an element to a container. An output iterator can move
only in the forward direction one element at a time. Output iterators
support only one-pass algorithms—the same output iterator cannot be
used to pass through a sequence twice.
Combines the capabilities of input and output iterators and retains
their position in the container (as state information).
Combines the capabilities of a forward iterator with the ability to move
in the backward direction (i.e., from the end of the container toward
the beginning). Bidirectional iterators support multipass algorithms.
Combines the capabilities of a bidirectional iterator with the ability to
directly access any element of the container, i.e., to jump forward or
backward by an arbitrary number of elements.
output
forward
bidirectional
random access
Fig. 22.6 | Iterator categories.
 2008 Pearson Education, Inc. All rights reserved.
37
Fig. 22.7 | Iterator category hierarchy.
 2008 Pearson Education, Inc. All rights reserved.
38
Software Engineering Observation 22.4
Using the “weakest iterator” that yields
acceptable performance helps produce maximally
reusable components. For example, if an
algorithm requires only forward iterators, it can
be used with any container that supports forward
iterators, bidirectional iterators or random-access
iterators. However, an algorithm that requires
random-access iterators can be used only with
containers that have random-access iterators.
 2008 Pearson Education, Inc. All rights reserved.
39
Container
Type of iterator supported
Sequence containers (first class)
Vector
Deque
List
random access
random access
bidirectional
Associative containers (first class)
set
multiset
map
multimap
bidirectional
bidirectional
bidirectional
bidirectional
Container adapters
stack
queue
priority_queue
no iterators supported
no iterators supported
no iterators supported
Fig. 22.8 | Iterator types supported by each Standard Library container.
 2008 Pearson Education, Inc. All rights reserved.
40
Predefined typedefs for iterator types
Direction of ++
Capability
iterator
forward
read/write
const_iterator
forward
read
reverse_iterator
backward
read/write
const_reverse_iterator
backward
read
Fig. 22.9 | Iterator typedefs.
 2008 Pearson Education, Inc. All rights reserved.
41
Error-Prevention Tip 22.3
Operations performed on a const_iterator
return const references to prevent modification
to elements of the container being manipulated.
Using const_iterators in preference to
iterators where appropriate is another
example of the principle of least privilege.
 2008 Pearson Education, Inc. All rights reserved.
42
Iterator operation
Description
All iterators
++p
p++
Preincrement an iterator.
Postincrement an iterator.
Input iterators
*p
p = p1
p == p1
p != p1
Dereference an iterator.
Assign one iterator to another.
Compare iterators for equality.
Compare iterators for inequality.
Output iterators
*p
P = p1
Dereference an iterator.
Assign one iterator to another.
Forward iterators
Bidirectional iterators
--p
p--
Forward iterators provide all the functionality of both input
iterators and output iterators.
Predecrement an iterator.
Postdecrement an iterator.
Fig. 22.10 | Iterator operations for each type of iterator. (Part 1 of 2 )
 2008 Pearson Education, Inc. All rights reserved.
43
Iterator operation
Description
Random-access iterators
p += i
p -= i
p + i
p - i
p[ i ]
p < p1
p <= p1
p > p1
p >= p1
Increment the iterator p by i positions.
Decrement the iterator p by i positions.
Expression value is an iterator positioned at p incremented by
i positions.
Expression value is an iterator positioned at p decremented
by i positions.
Return a reference to the element offset from p by i positions
Return true if iterator p is less than iterator p1 (i.e., iterator
p is before iterator p1 in the container); otherwise, return
false.
Return true if iterator p is less than or equal to iterator p1
(i.e., iterator p is before iterator p1 or at the same location as
iterator p1 in the container); otherwise, return false.
Return true if iterator p is greater than iterator p1 (i.e.,
iterator p is after iterator p1 in the container); otherwise,
return false.
Return true if iterator p is greater than or equal to iterator
p1 (i.e., iterator p is after iterator p1 or at the same location
as iterator p1 in the container); otherwise, return false.
Fig. 22.10 | Iterator operations for each type of iterator. (Part 2 of 2 )
 2008 Pearson Education, Inc. All rights reserved.
44
22.1.3 Introduction to Algorithms
• STL algorithms
– Can be used generically across many containers
• Inserting, deleting, searching, sorting, etc.
– Operate on container elements only indirectly through
iterators
• Many operate on sequences defined by pairs of iterators
– First iterator points to first element of sequence
– Second iterator points one past last element of sequence
• Often return iterators to indicate results
• Can be used on containers that support the necessary
iterator, or containers that support more powerful iterators
 2008 Pearson Education, Inc. All rights reserved.
45
Software Engineering Observation 22.5
The STL is implemented concisely. Until now, class
designers would have associated the algorithms
with the containers by making the algorithms
member functions of the containers. The STL takes
a different approach. The algorithms are separated
from the containers and operate on elements of the
containers only indirectly through iterators. This
separation makes it easier to write generic
algorithms applicable to many container classes.
 2008 Pearson Education, Inc. All rights reserved.
46
Software Engineering Observation 22.6
The STL is extensible. It is straightforward
to add new algorithms and to do so without
changes to STL containers.
 2008 Pearson Education, Inc. All rights reserved.
47
Software Engineering Observation 22.7
STL algorithms can operate on STL containers
and on pointer-based, C-like arrays.
 2008 Pearson Education, Inc. All rights reserved.
48
Portability Tip 22.2
Because STL algorithms process containers only
indirectly through iterators, one algorithm can
often be used with many different containers.
 2008 Pearson Education, Inc. All rights reserved.
49
Mutating-sequence algorithms
copy
remove
reverse_copy
copy_backward
fill
remove_copy
remove_copy_if
rotate
rotate_copy
fill_n
remove_if
stable_partition
generate
replace
swap
generate_n
replace_copy
swap_ranges
iter_swap
replace_copy_if
transform
partition
replace_if
unique
random_shuffle
reverse
unique_copy
Fig. 22.11 | Mutating-sequence algorithms.
 2008 Pearson Education, Inc. All rights reserved.
50
Nonmodifying sequence algorithms
adjacent_find
find
find_if
count
find_each
mismatch
count_if
find_end
search
equal
find_first_of
search_n
Fig. 22.12 | Nonmutating sequence algorithms.
 2008 Pearson Education, Inc. All rights reserved.
51
Numerical algorithms from header file <numeric>
accumulate
partial_sum
inner_product
adjacent_difference
Fig. 22.13 | Numerical algorithms from header file <numeric>.
 2008 Pearson Education, Inc. All rights reserved.
52
22.2 Sequence Containers
• STL sequence containers
– Three sequence containers
• vector – a more robust type of array
• list – implements a linked-list data structure
• deque – based on arrays
– Common operations of sequence containers
• front returns reference to first element
• back returns reference to last element
• push_back inserts new element to the end
• pop_back removes last element
 2008 Pearson Education, Inc. All rights reserved.
53
Performance Tip 22.4
Insertion at the back of a vector is efficient.
The vector simply grows, if necessary, to
accommodate the new item. It is expensive to
insert (or delete) an element in the middle of a
vector—the entire portion of the vector
after the insertion (or deletion) point must be
moved, because vector elements occupy
contiguous cells in memory just as C or C++
“raw” arrays do.
 2008 Pearson Education, Inc. All rights reserved.
54
Performance Tip 22.5
Applications that require frequent insertions and
deletions at both ends of a container normally use
a deque rather than a vector. Although we can
insert and delete elements at the front and back
of both a vector and a deque, class deque is
more efficient than vector for doing insertions
and deletions at the front.
 2008 Pearson Education, Inc. All rights reserved.
55
Performance Tip 22.6
Applications with frequent insertions and
deletions in the middle and/or at the extremes
of a container normally use a list, due to its
efficient implementation of insertion and
deletion anywhere in the data structure.
 2008 Pearson Education, Inc. All rights reserved.
56
22.2.1 vector Sequence Container
• Class template vector
– A data structure with contiguous memory locations
• Efficient, direct access to any element via subscript operator
– Or member function at, which provides range-checking
– Commonly used when data must be sorted and easily
accessible via subscript
– When additional memory is needed
• Allocates larger contiguous memory, copies elements and
deallocates old memory
– Supports random-access iterators
• All STL algorithms can operate on vectors
– Requires header file <vector>
 2008 Pearson Education, Inc. All rights reserved.
57
Performance Tip 22.7
Choose the vector container for the best
random-access performance.
 2008 Pearson Education, Inc. All rights reserved.
58
Performance Tip 22.8
Objects of class template vector provide rapid
indexed access with the overloaded subscript
operator [] because they are stored in contiguous
memory like a C or C++ raw array.
 2008 Pearson Education, Inc. All rights reserved.
59
Performance Tip 22.9
It is faster to insert many elements at once than
one at a time.
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.14: Fig22_14.cpp
2
3
4
// Demonstrating Standard Library vector class template.
#include <iostream>
using std::cout;
5
using std::endl;
6
7
8
9
#include <vector> // vector class-template definition
using std::vector;
60
Outline
Fig22_14.cpp
(1 of 3)
10 // prototype for function template printVector
11 template < typename T > void printVector( const vector< T > &integers2 );
12
13 int main()
14 {
Define a vector called integers
that stores int values
15
16
17
18
const int SIZE = 6; // define array size
int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; // initialize array
vector< int > integers; // create vector of ints
19
20
cout << "The initial size of integers is: " << integers.size()
<< "\nThe initial capacity of integers is: " << integers.capacity();
21
22
23
// function push_back is in every sequence collection
integers.push_back( 2 );
24
integers.push_back( 3 );
25
26
integers.push_back( 4 );
27
cout << "\nThe size of integers is: " << integers.size()
28
29
<< "\nThe capacity of integers is: " << integers.capacity();
cout << "\n\nOutput array using pointer notation: ";
Return the number of
elements currently
stored in the container
Return the number of elements that can be stored in the
vector before it needs to dynamically resize itself
Add elements to the end of the vector
to accommodate more elements
 2008 Pearson Education,
Inc. All rights reserved.
30
31
// display array using pointer notation
32
33
for ( int *ptr = array; ptr != array + SIZE; ptr++ )
cout << *ptr << ' ';
34
35
36
37
38
39
40
41
cout << "\nOutput vector using iterator notation: ";
printVector( integers );
cout << "\nReversed contents of vector integers: ";
Outline
Fig22_14.cpp
(2 of 3)
// two const reverse iterators
vector< int >::const_reverse_iterator reverseIterator;
vector< int >::const_reverse_iterator tempIterator = integers.rend();
42
43
// display vector in reverse order using reverse_iterator
44
45
for ( reverseIterator = integers.rbegin();
reverseIterator!= tempIterator; ++reverseIterator )
46
61
cout << *reverseIterator << ' ';
47
48
cout << endl;
49
return 0;
50 } // end main
reverseIterator iterates from the position returned
by rbegin until just before the position returned by
rend to output the vector elements in reverse order
 2008 Pearson Education,
Inc. All rights reserved.
51
62
52 // function template for outputting vector elements
53 template < typename T > void printVector( const vector< T > &integers2 )
Outline
54 {
55
typename vector< T >::const_iterator constIterator; // const_iterator
Fig22_14.cpp
56
57
// display vector elements using const_iterator
58
for ( constIterator = integers2.begin();
59
constIterator != integers2.end(); ++constIterator )
60
cout << *constIterator << ' ';
61 } // end function printVector
The
The
The
The
initial size of integers is: 0
initial capacity of integers is: 0
size of integers is: 3
capacity of integers is: 4
Output array using pointer notation: 1 2 3 4 5 6
Output vector using iterator notation: 2 3 4
Reversed contents of vector integers: 4 3 2
Tell the compiler that vector< T >
(3 of 3)
::const_iterator is expected
to be a type in every specialization
constIterator iterates through the
vector and outputs its contents
The vector’s capacity increases to
accommodate the growing size
 2008 Pearson Education,
Inc. All rights reserved.
63
Performance Tip 22.10
It can be wasteful to double a vector’s size
when more space is needed. For example, a full
vector of 1,000,000 elements resizes to
accommodate 2,000,000 elements when a new
element is added. This leaves 999,999 unused
elements. Programmers can use resize to
control space usage better.
 2008 Pearson Education, Inc. All rights reserved.
64
Performance Tip 22.11
Use prefix increment when applied to STL
iterators because the prefix increment operator
does not return a value that must be stored in a
temporary object.
 2008 Pearson Education, Inc. All rights reserved.
22.2.1 vector Sequence Container
(Cont.)
65
• Class template vector (Cont.)
– Member function insert
• Inserts a value at location specified by iterator argument
• Overloaded versions
– Insert multiple copies of a value
– Insert a range of values from another container
– Member function erase
• Remove the element at location specified by iterator
argument
• Or remove a range of elements specified by two iterator
arguments
 2008 Pearson Education, Inc. All rights reserved.
22.2.1 vector Sequence Container
(Cont.)
66
• STL algorithm function copy
– Copies each element in the specified container into the
other specified container
• First and second arguments specify source container
– Must be at least input iterators
• Third argument specifies beginning of destination container
– Must be at least output iterator
– Requires header file <algorithm>
 2008 Pearson Education, Inc. All rights reserved.
67
Error-Prevention Tip 22.4
Only random-access iterators support <. It is
better to use != and end to test for the end
of a container.
 2008 Pearson Education, Inc. All rights reserved.
68
Performance Tip 22.12
For performance reasons, capture the loop
ending value before the loop and compare
against that, rather than having a (potentially
expensive) function call for each iteration.
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.15: Fig22_15.cpp
// Testing Standard Library vector class template
3
// element-manipulation functions.
4
5
#include <iostream>
using std::cout;
6
7
8
using std::endl;
69
Outline
Fig22_15.cpp
<algorithm> must be included
to use STL algorithms(1 of 3)
#include <vector> // vector class-template definition
9 #include <algorithm> // copy algorithm
10 #include <iterator> // ostream_iterator iterator
11 #include <stdexcept> // out_of_range exception
12
13 int main()
Initialize integers with the contents
of array from location array up to
just before location array + SIZE
14 {
15
const int SIZE = 6;
16
17
18
int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
std::vector< int > integers( array, array + SIZE );
std::ostream_iterator< int > output( cout, " " );
19
20
21
cout << "Vector integers contains: ";
std::copy( integers.begin(), integers.end(), output );
22
23
cout << "\nFirst element of integers: " << integers.front()
24
25
output can be used to output integers
separated by single spaces via cout
<< "\nLast element of integers: " << integers.back();
26
integers[ 0 ] = 7; // set first element to 7
27
28
29
integers.at( 2 ) = 10; // set element at position 2 to 10
30
integers.insert( integers.begin() + 1, 22 );
// insert 22 as 2nd element
Copy the entire contents of vector
integers to the standard output
References to first and last
elements of integers
Access individual elements of integers
Insert 22 as the second element
 2008 Pearson Education,
Inc. All rights reserved.
31
32
cout << "\n\nContents of vector integers after changes: ";
33
std::copy( integers.begin(), integers.end(), output );
70
Outline
34
35
36
// access out-of-range element
try
37
38
39
40
41
{
42
Member function at throws an
out_of_range exception
integers.at( 100 ) = 777;
} // end try
catch ( std::out_of_range outOfRange ) // out_of_range exception
{
Fig22_15.cpp
(2 of 3)
cout << "\n\nException: " << outOfRange.what();
43
} // end catch
44
45
46
// erase first element
integers.erase( integers.begin() );
47
cout << "\n\nVector integers after erasing first element: ";
48
49
50
51
52
std::copy( integers.begin(), integers.end(), output );
// erase remaining elements
integers.erase( integers.begin(), integers.end() );
cout << "\nAfter erasing all elements, vector integers "
53
<< ( integers.empty() ? "is" : "is not" ) << " empty";
54
55
56
// insert elements from array
integers.insert( integers.begin(), array, array + SIZE );
57
58
cout << "\n\nContents of vector integers before clear: ";
std::copy( integers.begin(), integers.end(), output );
Remove the element at the
beginning of integers
Erase all elements of integers
Confirm that the vector is empty
Insert all of array at the
beginning of integers
 2008 Pearson Education,
Inc. All rights reserved.
59
71
60
// empty integers; clear calls erase to empty a collection
61
integers.clear();
62
cout << "\nAfter clear, vector integers "
63
64
Outline
Empty the vector
<< ( integers.empty() ? "is" : "is not" ) << " empty" << endl;
return 0;
Fig22_15.cpp
65 } // end main
Vector integers contains: 1 2 3 4 5 6
First element of integers: 1
Last element of integers: 6
(3 of 3)
Contents of vector integers after changes: 7 22 2 10 4 5 6
Exception: invalid vector<T> subscript
Vector integers after erasing first element: 22 2 10 4 5 6
After erasing all elements, vector integers is empty
Contents of vector integers before clear: 1 2 3 4 5 6
After clear, vector integers is empty
 2008 Pearson Education,
Inc. All rights reserved.
72
Common Programming Error 22.3
The vector must not be empty; otherwise,
results of the front and back functions are
undefined.
 2008 Pearson Education, Inc. All rights reserved.
73
Common Programming Error 22.4
Erasing an element that contains a pointer to a
dynamically allocated object does not delete
that object; this can lead to a memory leak.
 2008 Pearson Education, Inc. All rights reserved.
74
STL exception types
Description
out_of_range
Indicates when subscript is out of range—e.g., when an
invalid subscript is specified to vector member function
at.
Indicates an invalid argument was passed to a function.
Indicates an attempt to create too long a container, string,
etc.
Indicates that an attempt to allocate memory with s (or with
an allocator) failed because not enough memory was
available.
invalid_argument
length_error
bad_alloc
Fig. 22.16 | Some STL exception types.
 2008 Pearson Education, Inc. All rights reserved.
75
22.2.2 list Sequence Container
• Class template list
– Implemented as a doubly-linked list
• Provides efficient insertion and deletion operations at any
location
– Supports bidirectional iterators
• Can be traversed forward and backward
– Requires header file <list>
 2008 Pearson Education, Inc. All rights reserved.
76
22.2.2 list Sequence Container (Cont.)
• Class template list (Cont.)
– Member function sort
• Arranges the elements in the list in ascending order
• Can take a binary predicate function as second argument to
determine sorting order
– Member function splice
• Removes elements from the container argument and inserts
them into the current list at the specified location
• Overloaded versions
– Three arguments - third argument specifies a single
element in the container argument to splice
– Four arguments - third and fourth arguments specify a
range of elements in the container argument to splice
 2008 Pearson Education, Inc. All rights reserved.
77
22.2.2 list Sequence Container (Cont.)
• Class template list (Cont.)
– Member function merge
• Removes elements from the specified list and inserts them
in sorted order into the current list
– Both lists must first be sorted in the same order
• Can take a binary predicate function as second argument to
determine sorting order
– Member function unique
• Removes duplicate elements from the list
– list must first be sorted
• A second argument can specify a binary predicate function to
determine whether two elements are equal
 2008 Pearson Education, Inc. All rights reserved.
78
22.2.2 list Sequence Container (Cont.)
• Class template list (Cont.)
– Member function assign
• Replaces contents of the current list with values from the
range specified by two iterator arguments
• Overloaded version
– Replaces contents with copies of a value
• First argument specifies number of copies
• Second argument specifies the value to assign
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.17: Fig22_17.cpp
2
// Standard library list class template test program.
3
#include <iostream>
4
5
6
using std::cout;
using std::endl;
79
Outline
Fig22_17.cpp
7 #include <list> // list class-template definition
8 #include <algorithm> // copy algorithm
9 #include <iterator> // ostream_iterator
10
(1 of 5)
11 // prototype for function template printList
12 template < typename T > void printList( const std::list< T > &listRef );
13
14 int main()
15 {
16
17
18
const int SIZE = 4;
int array[ SIZE ] = { 2, 6, 4, 8 };
std::list< int > values; // create list of ints
19
20
21
22
std::list< int > otherValues; // create list of ints
23
24
25
26
values.push_front( 2 );
values.push_back( 4 );
values.push_back( 3 );
27
28
cout << "values contains: ";
printList( values );
Instantiate two list objects
capable of storing integers
// insert items in values
values.push_front( 1 );
Insert integers at the beginning and end of values
 2008 Pearson Education,
Inc. All rights reserved.
29
80
30
values.sort(); // sort values
31
cout << "\nvalues after sorting contains: ";
32
33
printList( values );
34
35
36
37
38
// insert elements of array into otherValues
otherValues.insert( otherValues.begin(), array, array + SIZE );
cout << "\nAfter insert, otherValues contains: ";
printList( otherValues );
39
40
// remove otherValues elements and insert at end of values
values.splice( values.end(), otherValues );
41
42
43
44
cout << "\nAfter splice, values contains: ";
printList( values );
45
cout << "\nAfter sort, values contains: ";
46
47
48
49
50
51
52
printList( values );
Arrange the elements in the
list in ascending order
Outline
Fig22_17.cpp
(2 of 5)
Remove the elements in otherValues
and insert them at the end of values
values.sort(); // sort values
// insert elements of array into otherValues
otherValues.insert( otherValues.begin(), array, array + SIZE );
otherValues.sort();
cout << "\nAfter insert, otherValues contains: ";
printList( otherValues );
 2008 Pearson Education,
Inc. All rights reserved.
53
54
55
// remove otherValues elements and insert into values in sorted order
values.merge( otherValues );
56
cout << "\nAfter merge:\n
57
58
59
60
61
62
63
printList( values );
cout << "\n
otherValues contains: ";
printList( otherValues );
64
65
printList( values );
66
values.unique(); // remove duplicate elements
67
68
69
70
cout << "\nAfter unique, values contains: ";
printList( values );
71
72
73
values.swap( otherValues );
cout << "\nAfter swap:\n
values contains: ";
printList( values );
74
75
cout << "\n
otherValues contains: ";
printList( otherValues );
values contains: ";
81
Outline
Remove all elements of otherValues and
insert them in sorted order in values
Fig22_17.cpp
values.pop_front(); // remove element from front
values.pop_back(); // remove element from back
cout << "\nAfter pop_front and pop_back:\n
values contains: "
(3 of 5)
Remove duplicate elements in values
// swap elements of values and otherValues
Exchange the contents of values with
the contents of otherValues
76
77
// replace contents of values with elements of otherValues
78
79
80
values.assign( otherValues.begin(), otherValues.end() );
cout << "\nAfter assign, values contains: ";
printList( values );
Replace the contents of values with
the elements in otherValues
 2008 Pearson Education,
Inc. All rights reserved.
81
82
// remove otherValues elements and insert into values in sorted order
83
84
85
86
87
88
89
90
values.merge( otherValues );
cout << "\nAfter merge, values contains: ";
printList( values );
Delete all copies of the
value 4 from values
values.remove( 4 ); // remove all 4s
cout << "\nAfter remove( 4 ), values contains: ";
printList( values );
cout << endl;
82
Outline
Fig22_17.cpp
(4 of 5)
91
return 0;
92 } // end main
93
94 // printList function template definition; uses
95 // ostream_iterator and copy algorithm to output list elements
96 template < typename T > void printList( const std::list< T > &listRef )
97 {
98
99
100
101
if ( listRef.empty() ) // list is empty
cout << "List is empty";
else
{
102
std::ostream_iterator< T > output( cout, " " );
103
std::copy( listRef.begin(), listRef.end(), output );
104
} // end else
105 } // end function printList
 2008 Pearson Education,
Inc. All rights reserved.
values contains: 2 1 4 3
values after sorting contains: 1 2 3 4
After insert, otherValues contains: 2 6 4 8
After splice, values contains: 1 2 3 4 2 6 4 8
After sort, values contains: 1 2 2 3 4 4 6 8
After insert, otherValues contains: 2 4 6 8
After merge:
values contains: 1 2 2 2 3 4 4 4 6 6 8 8
otherValues contains: List is empty
After pop_front and pop_back:
values contains: 2 2 2 3 4 4 4 6 6 8
After unique, values contains: 2 3 4 6 8
After swap:
values contains: List is empty
otherValues contains: 2 3 4 6 8
After assign, values contains: 2 3 4 6 8
After merge, values contains: 2 2 3 3 4 4 6 6 8 8
After remove( 4 ), values contains: 2 2 3 3 6 6 8 8
83
Outline
Fig22_17.cpp
(5 of 5)
 2008 Pearson Education,
Inc. All rights reserved.
84
22.2.3 deque Sequence Container
• Class template deque
– Provides many of the benefits of vector and list in one
container
• Efficient indexed access using subscripting
• Efficient insertion and deletion operations at front and back
– Supports random-access iterators
• All STL algorithms can be used on deques
– Additional storage may be allocated at either end
• Noncontiguous memory layout
– Requires header file <deque>
 2008 Pearson Education, Inc. All rights reserved.
85
Performance Tip 22.13
In general, deque has slightly higher overhead
than vector.
 2008 Pearson Education, Inc. All rights reserved.
86
Performance Tip 22.14
Insertions and deletions in the middle of a deque
are optimized to minimize the number of elements
copied, so it is more efficient than a vector but
less efficient than a list for this kind of
modification.
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.18: Fig22_18.cpp
2
3
4
// Standard Library class deque test program.
#include <iostream>
using std::cout;
5
using std::endl;
6
7
8
9
#include <deque> // deque class-template definition
#include <algorithm> // copy algorithm
#include <iterator> // ostream_iterator
10
11 int main()
12 {
87
Outline
Fig22_18.cpp
(1 of 2)
Instantiate a deque that
can store double values
13
14
std::deque< double > values; // create deque of doubles
std::ostream_iterator< double > output( cout, " " );
15
16
17
18
// insert elements in values
values.push_front( 2.2 );
values.push_front( 3.5 );
19
20
values.push_back( 1.1 );
21
22
23
cout << "values contains: ";
24
for ( unsigned int i = 0; i < values.size(); i++ )
25
26
Insert elements at the beginning
and end of the deque
// use subscript operator to obtain elements of values
cout << values[ i ] << ' ';
27
values.pop_front(); // remove first element
28
29
cout << "\nAfter pop_front, values contains: ";
std::copy( values.begin(), values.end(), output );
Retrieve the value in each element
of the deque for output
Remove the first element of the deque
 2008 Pearson Education,
Inc. All rights reserved.
30
31
// use subscript operator to modify element at location 1
32
33
values[ 1 ] = 5.4;
cout << "\nAfter values[ 1 ] = 5.4, values contains: ";
34
35
std::copy( values.begin(), values.end(), output );
cout << endl;
36
return 0;
37 } // end main
88
Outline
Use the subscript operator
to create an lvalue
Fig22_18.cpp
(2 of 2)
values contains: 3.5 2.2 1.1
After pop_front, values contains: 2.2 1.1
After values[ 1 ] = 5.4, values contains: 2.2 5.4
 2008 Pearson Education,
Inc. All rights reserved.
89
22.3 Associative Containers
• STL associative containers
– Provide direct access to store and retrieve elements via
keys (often called search keys)
• Maintain keys in sorted order
– Four associative containers
• multiset – stores keys only, allows duplicates
• set – stores keys only, no duplicates
• multimap – stores keys and associated values, allows
duplicates
• map – stores keys and associated values, no duplicates
– Common member functions
• find, lower_bound, upper_bound, count
 2008 Pearson Education, Inc. All rights reserved.
90
22.3.1 multiset Associative Container
•multiset associative container
– Provides fast storage and retrieval of keys and allows
duplicate keys
– Ordering of keys is determined by a comparator function
object
• Default is std::less< T > for ascending order
• Data type of the keys must support this function
– Supports bidirectional iterators
– Requires header file <set>
 2008 Pearson Education, Inc. All rights reserved.
91
Good Programming Practice 22.1
Use typedefs to make code with long type
names (such as multisets) easier to read.
 2008 Pearson Education, Inc. All rights reserved.
22.3.1 multiset Associative Container
(Cont.)
92
•multiset associative container (Cont.)
– Member function insert
• Adds a value to a set or multiset
• Overloaded versions
– Second version – an iterator argument specifies the
location to begin searching for the insertion point
– Third version – two iterator arguments specify a range
of values to add from another container
– Member function find
• Locates a value in the associative container
– Returns an iterator to its earliest occurrence
– Returns the iterator returned by end if the value is
not found
 2008 Pearson Education, Inc. All rights reserved.
22.3.1 multiset Associative Container
(Cont.)
93
•multiset associative container (Cont.)
– Member function lower_bound
• Locates earliest occurrence of a value
– Returns an iterator to that position
– Returns the iterator returned by end if the value is
not found
– Member function upper_bound
• Locates element after the last occurrence of a value
– Returns an iterator to that position
– Returns the iterator returned by end if the value is
not found
 2008 Pearson Education, Inc. All rights reserved.
22.3.1 multiset Associative Container
(Cont.)
94
•multiset associative container (Cont.)
– Member function equal_range
• Returns pair object containing the results of lower_bound
and upper_bound
– pair data member first stores lower_bound
– pair data member second stores upper_bound
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.19: Fig22_19.cpp
2
// Testing Standard Library class multiset
3
#include <iostream>
4
5
6
using std::cout;
using std::endl;
95
Outline
7 #include <set> // multiset class-template definition
8
9 // define short name for multiset type used in this program
10 typedef std::multiset< int, std::less< int > > Ims;
11
12 #include <algorithm> // copy algorithm
13 #include <iterator> // ostream_iterator
14
Fig22_19.cpp
(1 of 3)
Create a new type name for a multiset
of integers in ascending order
15 int main()
16 {
17
const int SIZE = 10;
18
int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 };
19
20
21
22
Ims intMultiset; // Ims is typedef for "integer multiset"
std::ostream_iterator< int > output( cout, " " );
Count the number of occurrences of
the value 15 in intMultiset
cout << "There are currently " << intMultiset.count( 15 )
<< " values of 15 in the multiset\n";
23
24
25
26
intMultiset.insert( 15 ); // insert 15 in intMultiset
intMultiset.insert( 15 ); // insert 15 in intMultiset
27
28
cout << "After inserts, there are " << intMultiset.count( 15 )
<< " values of 15 in the multiset\n\n";
Add the value 15 to
intMultiset twice
 2008 Pearson Education,
Inc. All rights reserved.
29
30
31
32
33
34
35
36
37
38
39
// find 15 in intMultiset; find returns iterator
result = intMultiset.find( 15 );
Locate the value 15
in intMultiset
Fig22_19.cpp
if ( result != intMultiset.end() ) // if iterator not at end
cout << "Found value 15\n"; // found search value 15
(2 of 3)
// find 20 in intMultiset; find returns iterator
result = intMultiset.find( 20 );
42
43
if ( result == intMultiset.end() ) // will be true hence
cout << "Did not find value 20\n"; // did not find 20
53
54
55
56
Outline
Ims::const_iterator result;
40
41
44
45
46
47
48
49
50
51
52
96
// iterator that cannot be used to change element values
// insert elements of array a into intMultiset
intMultiset.insert( a, a + SIZE );
cout << "\nAfter insert, intMultiset contains:\n";
std::copy( intMultiset.begin(), intMultiset.end(), output );
// determine lower and upper bound of 22 in intMultiset
cout << "\n\nLower bound of 22: "
<< *( intMultiset.lower_bound( 22 ) );
Insert the elements of array
a into intMultiset
Locate the earliest occurrence of
the value 22 in intMultiset
cout << "\nUpper bound of 22: " << *( intMultiset.upper_bound( 22 ) );
// p represents pair of const_iterators
std::pair< Ims::const_iterator, Ims::const_iterator > p;
Locate the position after the last
occurrence of the value 22 in
intMultiset
 2008 Pearson Education,
Inc. All rights reserved.
57
58
// use equal_range to determine lower and upper bound
59
// of 22 in intMultiset
60
61
62
p = intMultiset.equal_range( 22 );
cout << "\n\nequal_range of 22:" << "\n
63
64
<< *( p.first ) << "\n
cout << endl;
97
Outline
Obtain the results of both
a lower_bound
and an upper_bound operation from a
single function call
Lower bound: "
Upper bound: " << *( p.second );
65
return 0;
66 } // end main
There are currently 0 values of 15 in the multiset
After inserts, there are 2 values of 15 in the multiset
Fig22_19.cpp
(3 of 3)
A pair contains two public data
members, first and second
Found value 15
Did not find value 20
After insert, intMultiset contains:
1 7 9 13 15 15 18 22 22 30 85 100
Lower bound of 22: 22
Upper bound of 22: 30
equal_range of 22:
Lower bound: 22
Upper bound: 30
 2008 Pearson Education,
Inc. All rights reserved.
98
22.3.2 set Associative Container
•set associative container
– Used for fast storage and retrieval of unique keys
• Does not allow duplicate keys
– An attempt to insert a duplicate key is ignored
– Supports bidirectional iterators
– Requires header file <set>
– Member function insert
• Inserts a value into the set
• Returns a pair object
– pair member first is an iterator pointing to the
element with that value inside the set
– pair member second is a bool indicating whether the
value was inserted
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.20: Fig22_20.cpp
// Standard Library class set test program.
3
#include <iostream>
4
5
6
using std::cout;
using std::endl;
99
Outline
7 #include <set>
8
9 // define short name for set type used in this program
10 typedef std::set< double, std::less< double > > DoubleSet;
Fig22_20.cpp
(1 of 2)
11
12 #include <algorithm>
13 #include <iterator> // ostream_iterator
14
Create a new type name for a set of
double values ordered in ascending order
15 int main()
16 {
17
const int SIZE = 5;
18
double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 };
19
DoubleSet doubleSet( a, a + SIZE );
20
std::ostream_iterator< double > output( cout, " " );
21
22
cout << "doubleSet contains: ";
23
std::copy( doubleSet.begin(), doubleSet.end(), output );
24
25
26
// p represents pair containing const_iterator and bool
std::pair< DoubleSet::const_iterator, bool > p;
Second 2.1 value (a duplicate)
will be ignored
Define a pair object to store the result
of set member function insert
 2008 Pearson Education,
Inc. All rights reserved.
27
28
// insert 13.8 in doubleSet; insert returns pair in which
29
30
31
// p.first represents location of 13.8 in doubleSet and
// p.second represents whether 13.8 was inserted
p = doubleSet.insert( 13.8 ); // value not in set
32
33
34
35
cout << "\n\n" << *( p.first )
<< ( p.second ? " was" : " was not" ) << " inserted";
cout << "\ndoubleSet contains: ";
std::copy( doubleSet.begin(), doubleSet.end(), output );
36
37
// insert 9.5 in doubleSet
38
39
p = doubleSet.insert( 9.5 ); // value already in set
cout << "\n\n" << *( p.first )
40
41
42
<< ( p.second ? " was" : " was not" ) << " inserted";
cout << "\ndoubleSet contains: ";
std::copy( doubleSet.begin(), doubleSet.end(), output );
43
44
cout << endl;
return 0;
100
Outline
Iterator p.first points to
the value 13.8Fig22_20.cpp
in the set
(2 of 2) is true
bool value p.second
if the value was inserted
45 } // end main
doubleSet contains: 2.1 3.7 4.2 9.5
13.8 was inserted
doubleSet contains: 2.1 3.7 4.2 9.5 13.8
9.5 was not inserted
doubleSet contains: 2.1 3.7 4.2 9.5 13.8
 2008 Pearson Education,
Inc. All rights reserved.
101
22.3.3 multimap Associative Container
•multimap associative container
– Used for fast storage and retrieval of keys and associated
values (key/value pairs)
• Stored as pair objects
• Duplicate keys are allowed (one-to-many mapping)
– Multiple values can be associated with a single key
– Ordering of keys is determined by a comparator function
object
– Supports bidirectional iterators
– Requires header file <map>
 2008 Pearson Education, Inc. All rights reserved.
102
Performance Tip 22.15
A multimap is implemented to efficiently
locate all values paired with a given key.
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.21: Fig22_21.cpp
// Standard Library class multimap test program.
3
4
#include <iostream>
using std::cout;
5
6
using std::endl;
7
8
#include <map> // map class-template definition
103
Outline
Define an alias for a multimap type with int
keys and double values, in ascending order
9 // define short name for multimap type used in this program
10 typedef std::multimap< int, double, std::less< int > > Mmid;
11
12 int main()
13 {
14
Mmid pairs; // declare the multimap pairs
15
16
17
cout << "There are currently " << pairs.count( 15 )
<< " pairs with key 15 in the multimap\n";
18
19
20
// insert two value_type objects in pairs
pairs.insert( Mmid::value_type( 15, 2.7 ) );
21
22
pairs.insert( Mmid::value_type( 15, 99.3 ) );
23
24
cout << "After inserts, there are " << pairs.count( 15 )
<< " pairs with key 15\n\n";
Fig22_21.cpp
(1 of 2)
Determine the number of key/value
pairs with a key of 15
Add new key/value pairs
to the multimap
Create a pair object in which
first is the int key 15 and
second is the double value 2.7
 2008 Pearson Education,
Inc. All rights reserved.
25
26
// insert five value_type objects in pairs
27
pairs.insert( Mmid::value_type( 30, 111.11 ) );
28
29
30
pairs.insert( Mmid::value_type( 10, 22.22 ) );
pairs.insert( Mmid::value_type( 25, 33.333 ) );
pairs.insert( Mmid::value_type( 20, 9.345 ) );
31
32
pairs.insert( Mmid::value_type( 5, 77.54 ) );
33
34
35
cout << "Multimap pairs contains:\nKey\tValue\n";
36
37
for ( Mmid::const_iterator iter = pairs.begin();
iter != pairs.end(); ++iter )
104
Outline
Fig22_21.cpp
(2 of 2)
// use const_iterator to walk through elements of pairs
38
cout << iter->first << '\t' << iter->second << '\n';
39
40
cout << endl;
41
return 0;
42 } // end main
Use const_iterator iter to
access the keys and values in pairs
There are currently 0 pairs with key 15 in the multimap
After inserts, there are 2 pairs with key 15
Multimap pairs contains:
Key
Value
5
77.54
10
22.22
15
2.7
15
99.3
20
9.345
25
33.333
30
111.11
 2008 Pearson Education,
Inc. All rights reserved.
105
22.3.4 map Associative Container
•map associative container
– Used for fast storage and retrieval of keys and associated
values (key/value pairs)
• Stored as pair objects
• Duplicate keys are not allowed (one-to-one mapping)
– Only one value can be associated with each key
– Commonly called an associative array
• Inserting a new key/value pair is called creating an
association
– Insertions and deletions can be made anywhere
– Requires header file <map>
 2008 Pearson Education, Inc. All rights reserved.
106
22.3.4 map Associative Container (Cont.)
•map associative container (Cont.)
– Subscript operator [] can locate the value associated with
a given key
• When the key is already in the map
– Returns a reference to the associated value
• When the key is not in the map
– Inserts the key in the map
– Returns a reference to the associated value (so it can be
set)
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.22: Fig22_22.cpp
// Standard Library class map test program.
3
#include <iostream>
4
5
using std::cout;
using std::endl;
6
7
8
9
#include <map> // map class-template definition
// define short name for map type used in this program
107
Outline
Fig22_22.cpp
(1 of 3)
10 typedef std::map< int, double, std::less< int > > Mid;
11
12 int main()
13 {
14
Mid pairs;
15
16
17
18
19
20
21
// insert eight value_type objects in pairs
pairs.insert( Mid::value_type( 15, 2.7 ) );
pairs.insert( Mid::value_type( 30, 111.11 ) );
pairs.insert( Mid::value_type( 5, 1010.1 ) );
pairs.insert( Mid::value_type( 10, 22.22 ) );
pairs.insert( Mid::value_type( 25, 33.333 ) );
22
23
pairs.insert( Mid::value_type( 5, 77.54 ) ); // dup ignored
pairs.insert( Mid::value_type( 20, 9.345 ) );
24
25
26
pairs.insert( Mid::value_type( 15, 99.3 ) ); // dup ignored
cout << "pairs contains:\nKey\tValue\n";
 2008 Pearson Education,
Inc. All rights reserved.
27
108
28
// use const_iterator to walk through elements of pairs
29
for ( Mid::const_iterator iter = pairs.begin();
30
iter != pairs.end(); ++iter )
31
cout << iter->first << '\t' << iter->second << '\n';
32
Outline
Replace the value for the key 25
with the new value
9999.99
Fig22_22.cpp
33
pairs[ 25 ] = 9999.99; // use subscripting to change value for key 25
34
pairs[ 40 ] = 8765.43; // use subscripting to insert value for key 40
(2 of 3)
35
36
cout << "\nAfter subscript operations, pairs contains:\nKey\tValue\n";
37
38
// use const_iterator to walk through elements of pairs
39
for ( Mid::const_iterator iter2 = pairs.begin();
40
iter2 != pairs.end(); ++iter2 )
41
cout << iter2->first << '\t' << iter2->second << '\n';
Insert a new key/value
pair in the map
42
43
cout << endl;
44
return 0;
45 } // end main
 2008 Pearson Education,
Inc. All rights reserved.
pairs contains:
Key
Value
5
1010.1
10
22.22
15
2.7
20
9.345
25
33.333
30
111.11
After subscript operations, pairs contains:
Key
Value
5
1010.1
10
22.22
15
2.7
20
9.345
25
9999.99
30
111.11
40
8765.43
109
Outline
Fig22_22.cpp
(3 of 3)
 2008 Pearson Education,
Inc. All rights reserved.
110
22.4 Container Adapters
• STL container adapters
– Are not first-class containers
• Do not provide the actual data structure implementation
• Do not support iterators
– Programmer can choose an appropriate underlying data
structure
– Common member functions
• push
– Properly insert an element into data structure
• pop
– Properly remove an element from data structure
 2008 Pearson Education, Inc. All rights reserved.
111
22.4.1 stack Adapter
• Class stack
– Enables insertions and deletions at one end
• Last-in, first-out data structure
– Can be implemented with any sequence container
• Implemented with a deque by default
– Operations (call functions of the underlying container)
• push – insert element at top (calls push_back)
• pop – remove top element (calls pop_back)
• top – returns reference to top element (calls back)
• empty – determine if the stack is empty (calls empty)
• size – get the number of elements (calls size)
– Requires header file <stack>
 2008 Pearson Education, Inc. All rights reserved.
112
Performance Tip 22.16
Each of the common operations of a stack is
implemented as an inline function that calls the
appropriate function of the underlying container.
This avoids the overhead of a second function call.
 2008 Pearson Education, Inc. All rights reserved.
113
Performance Tip 22.17
For the best performance, use class deque or
vector as the underlying container for a stack.
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.23: Fig22_23.cpp
// Standard Library adapter stack test program.
3
#include <iostream>
4
5
using std::cout;
using std::endl;
6
7
8
9
#include <stack> // stack adapter definition
#include <vector> // vector class-template definition
#include <list> // list class-template definition
114
Outline
Fig22_23.cpp
(1 of 3)
10
11 // pushElements function-template prototype
12 template< typename T > void pushElements( T &stackRef );
13
14 // popElements function-template prototype
15 template< typename T > void popElements( T &stackRef );
16
17 int main()
18 {
19
// stack with default underlying deque
20
std::stack< int > intDequeStack;
21
22
23
// stack with underlying vector
std::stack< int, std::vector< int > > intVectorStack;
24
25
26
// stack with underlying list
std::stack< int, std::list< int > > intListStack;
Specify integer stacks using each of
the three sequence containers as the
underlying data structure
 2008 Pearson Education,
Inc. All rights reserved.
27
28
// push the values 0-9 onto each stack
29
cout << "Pushing onto intDequeStack: ";
30
pushElements( intDequeStack );
31
32
cout << "\nPushing onto intVectorStack: ";
pushElements( intVectorStack );
33
34
cout << "\nPushing onto intListStack: ";
pushElements( intListStack );
35
36
37
38
cout << endl << endl;
39
40
popElements( intDequeStack );
cout << "\nPopping from intVectorStack: ";
41
42
popElements( intVectorStack );
cout << "\nPopping from intListStack: ";
43
44
popElements( intListStack );
cout << endl;
115
Outline
Fig22_23.cpp
(2 of 3)
// display and remove elements from each stack
cout << "Popping from intDequeStack: ";
45
return 0;
46 } // end main
47
48 // push elements onto stack object to which stackRef refers
49 template< typename T > void pushElements( T &stackRef )
50 {
51
for ( int i = 0; i < 10; i++ )
52
{
Place an integer on
top of the stack
53
stackRef.push( i ); // push element onto stack
54
cout << stackRef.top() << ' '; // view (and display ) top element
55
} // end for
Retrieve, but not remove, the top
56 } // end function pushElements
element
 2008 Pearson Education,
Inc. All rights reserved.
57
58 // pop elements from stack object to which stackRef refers
59 template< typename T > void popElements( T &stackRef )
60 {
Retrieve and
61
while ( !stackRef.empty() )
62
63
64
{
65
} // end while
Outline
display the top element
cout << stackRef.top() << ' '; // view (and display) top element
stackRef.pop(); // remove top element
66 } // end function popElements
116
Fig22_23.cpp
(3 of 3)
Remove, and discard, the top element
Pushing onto intDequeStack: 0 1 2 3 4 5 6 7 8 9
Pushing onto intVectorStack: 0 1 2 3 4 5 6 7 8 9
Pushing onto intListStack: 0 1 2 3 4 5 6 7 8 9
Popping from intDequeStack: 9 8 7 6 5 4 3 2 1 0
Popping from intVectorStack: 9 8 7 6 5 4 3 2 1 0
Popping from intListStack: 9 8 7 6 5 4 3 2 1 0
 2008 Pearson Education,
Inc. All rights reserved.
117
22.4.2 queue Adapter
• Class queue
– Enables insertions at back and deletions from front
• First-in, first-out data structure
– Can be implemented with data structure list or deque
• Implemented with a deque by default
– Operations (call functions of the underlying container)
• push – insert element at back (calls push_back)
• pop – remove element from front (calls pop_front)
• front – returns reference to first element (calls front)
• empty – determine if the queue is empty (calls empty)
• size – get the number of elements (calls size)
– Requires header file <queue>
 2008 Pearson Education, Inc. All rights reserved.
118
Performance Tip 22.18
Each of the common operations of a queue is
implemented as an inline function that calls the
appropriate function of the underlying container.
This avoids the overhead of a second function call.
 2008 Pearson Education, Inc. All rights reserved.
119
Performance Tip 22.19
For the best performance, use class deque or
list as the underlying container for a queue.
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.24: Fig22_24.cpp
2
// Standard Library adapter queue test program.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
120
Outline
Fig22_24.cpp
6
7
#include <queue> // queue adapter definition
Instantiate a queue that
stores double values
8
9
int main()
(1 of 2)
10 {
11
std::queue< double > values; // queue with doubles
12
13
// push elements onto queue values
14
values.push( 3.2 );
15
values.push( 9.8 );
16
values.push( 5.4 );
Add elements to the queue
17
18
cout << "Popping from values: ";
 2008 Pearson Education,
Inc. All rights reserved.
19
121
20
// pop elements from queue
21
while ( !values.empty() )
22
{
Read the first element in
the queue for output
23
cout << values.front() << ' '; // view front element
24
values.pop(); // remove element
25
Outline
Fig22_24.cpp
} // end while
(2 of 2)
26
27
cout << endl;
28
return 0;
29 } // end main
Remove the first element
in the queue
Popping from values: 3.2 9.8 5.4
 2008 Pearson Education,
Inc. All rights reserved.
122
22.4.3 priority_queue Adapter
• Class priority_queue
– Enables insertions in sorted order and deletions from front
• Elements are inserted in priority order
• Highest-priority element will be the first to be removed
• Maintains sorted order via heapsort
– Heaps keep largest value at the front
– Comparison of elements is performed with comparator
function object less< T > by default
– Can be implemented with data structure vector or
deque
• Implemented with a vector by default
 2008 Pearson Education, Inc. All rights reserved.
123
22.4.3 priority_queue Adapter (Cont.)
• Class priority_queue (Cont.)
– Operations (call functions of the underlying container)
• push – insert element at appropriate location to maintain
sorted order (calls push_back, then reorders elements with
heapsort)
• pop – remove highest-priority element (moves top element of
heap to back, then calls pop_back)
• top – returns reference to top element (calls front)
• empty – determine if the priority_queue is empty (calls
empty)
• size – get the number of elements (calls size)
– Requires header file <queue>
 2008 Pearson Education, Inc. All rights reserved.
124
Performance Tip 22.20
Each of the common operations of a
priority_queue is implemented as an
inline function that calls the appropriate
function of the underlying container. This
avoids the overhead of a second function
call.
 2008 Pearson Education, Inc. All rights reserved.
125
Performance Tip 22.21
For the best performance, use class vector
or deque as the underlying container for a
priority_queue.
 2008 Pearson Education, Inc. All rights reserved.
1
2
3
// Fig. 22.25: Fig22_25.cpp
// Standard Library adapter priority_queue test program.
#include <iostream>
4
5
using std::cout;
using std::endl;
6
7
8
#include <queue> // priority_queue adapter definition
126
Outline
Instantiate a priority_queue thatFig22_25.cpp
stores double values using a vector
as the underlying data structure (1 of 1)
9 int main()
10 {
11
std::priority_queue< double > priorities; // create priority_queue
12
13
// push elements onto priorities
Add elements to the priority_queue
14
15
16
priorities.push( 3.2 );
priorities.push( 9.8 );
priorities.push( 5.4 );
17
18
cout << "Popping from priorities: ";
19
20
// pop element from priority_queue
21
22
while ( !priorities.empty() )
{
23
24
25
26
27
cout << priorities.top() << ' '; // view top element
priorities.pop(); // remove top element
} // end while
28
return 0;
Retrieve the highest-priority element in
the priority_queue for output
cout << endl;
29 } // end main
Remove the highest-priority element
in the priority_queue
Popping from priorities: 9.8 5.4 3.2
 2008 Pearson Education,
Inc. All rights reserved.
127
22.5 Algorithms
• STL algorithms
– Separates algorithms from the containers
• Elements of containers are accessed through iterators
• Much easier to add new algorithms
 2008 Pearson Education, Inc. All rights reserved.
128
Performance Tip 22.22
The STL is implemented for efficiency. It avoids
the overhead of virtual function calls.
 2008 Pearson Education, Inc. All rights reserved.
129
Software Engineering Observation 22.8
STL algorithms do not depend on the
implementation details of the containers on
which they operate. As long as the container’s
(or array’s) iterators satisfy the requirements of
the algorithm, STL algorithms can work on Cstyle, pointer-based arrays, on STL containers
and on user-defined data structures.
 2008 Pearson Education, Inc. All rights reserved.
130
Software Engineering Observation 22.9
Algorithms can be added easily to the STL
without modifying the container classes.
 2008 Pearson Education, Inc. All rights reserved.
22.5.1 fill, fill_n, generate and
generate_n
131
• STL algorithm function fill
– Sets every element in a range of container elements to a
specific value
• First and second arguments are iterators specifying the range
– Must be at least forward iterators
• Third argument is the value to set
• STL algorithm function fill_n
– Sets a specified number of container elements to a specific
value
• First argument is iterator specifying beginning of range
– Must be at least forward iterator
• Second argument specifies number of elements to fill
• Third argument is the value to set
 2008 Pearson Education, Inc. All rights reserved.
22.5.1 fill, fill_n, generate and
generate_n (Cont.)
132
• STL algorithm function generate
– Uses generator function to create values for every element
in a range of a container
• First and second arguments are iterators specifying the range
– Must be at least forward iterators
• Third argument is a pointer to a function
– This function should takes no arguments and return an
element value
 2008 Pearson Education, Inc. All rights reserved.
22.5.1 fill, fill_n, generate and
generate_n (Cont.)
133
• STL algorithm function generate_n
– Uses generator function to create values for a specified
number of container elements
• First argument is iterator specifying beginning of range
– Must be at least forward iterator
• Second argument specifies number of elements to fill
• Third argument is a pointer to a function
– This function should takes no arguments and return an
element value
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.26: Fig22_26.cpp
2
3
4
// Standard Library algorithms fill, fill_n, generate and generate_n.
#include <iostream>
using std::cout;
5
using std::endl;
6
7
8
9
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
#include <iterator> // ostream_iterator
134
Outline
Fig22_26.cpp
(1 of 2)
10
11 char nextLetter(); // prototype of generator function
12
13 int main()
14 {
Define a 10-element vector
that stores char values
15
16
17
18
std::vector< char > chars( 10 );
std::ostream_iterator< char > output( cout, " " );
std::fill( chars.begin(), chars.end(), '5' ); // fill chars with 5s
19
20
cout << "Vector chars after filling with 5s:\n";
std::copy( chars.begin(), chars.end(), output );
21
22
23
// fill first five elements of chars with As
std::fill_n( chars.begin(), 5, 'A' );
Place the character '5' in
every element of chars
Place the character 'A' in the
first five elements of chars
24
25
26
cout << "\n\nVector chars after filling five elements with As:\n";
std::copy( chars.begin(), chars.end(), output );
27
28
29
// generate values for all elements of chars with nextLetter
std::generate( chars.begin(), chars.end(), nextLetter );
Place the result of a call to generator
 2008 function
Pearson Education,
Inc.
rights reserved.
nextLetter in every element of All
chars
30
31
cout << "\n\nVector chars after generating letters A-J:\n";
32
std::copy( chars.begin(), chars.end(), output );
33
34
// generate values for first five elements of chars with nextLetter
35
36
37
std::generate_n( chars.begin(), 5, nextLetter );
cout << "\n\nVector chars after generating K-O for the"
38
<< " first five elements:\n";
Place the result of a call
39
std::copy( chars.begin(), chars.end(), output );
nextLetter in the
40
cout << endl;
41
return 0;
42 } // end main
135
Outline
Fig22_26.cpp
(2 of 2)
to generator function
first five elements of chars
43
44 // generator function returns next letter (starts with A)
45 char nextLetter()
46 {
47
static char letter = 'A';
48
return letter++;
49 } // end function nextLetter
Vector chars after filling with 5s:
5 5 5 5 5 5 5 5 5 5
Vector chars after filling five elements with As:
A A A A A 5 5 5 5 5
Vector chars after generating letters A-J:
A B C D E F G H I J
Vector chars after generating K-O for the first five elements:
K L M N O F G H I J
 2008 Pearson Education,
Inc. All rights reserved.
22.5.2 equal, mismatch and
lexicographical_compare
136
• STL algorithm function equal
– Compares two sequences of values for equality
• Iterator arguments
– First and second arguments specify first sequence
– Third argument specifies beginning of second sequence
– Must be at least input iterators
– Considers sequences of uneven length to be unequal
– Uses == operator to compare elements
• A fourth argument can specify a binary predicate function to
use instead
– Takes two element arguments and returns a bool
 2008 Pearson Education, Inc. All rights reserved.
22.5.2 equal, mismatch and
lexicographical_compare (Cont.)
137
• STL algorithm function mismatch
– Locates the earliest pair of corresponding elements in two
sequences that do not match
• Returns a pair of iterators indicating the mismatched
elements
• Iterator arguments
– First and second arguments specify first sequence
– Third argument specifies beginning of second sequence
– Must be at least input iterators
• If all elements match, the returned pair of iterators are the
last iterators for each sequence
– A fourth argument can specify a binary predicate function
• Takes two elements arguments and returns a bool
 2008 Pearson Education, Inc. All rights reserved.
22.5.2 equal, mismatch and
lexicographical_compare (Cont.)
138
• STL algorithm function
lexicographical_compare
– Compares the contents of two sequences
• Iterator arguments
– First and second arguments specify first sequence
– Third and fourth argument specify second sequence
– Must be at least input iterators
• Returns true if first sequence is less than second sequence
• Returns false if first sequence is greater than or equal to
second sequence
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.27: Fig22_27.cpp
// Standard Library functions equal, mismatch and lexicographical_compare.
3
#include <iostream>
4
5
using std::cout;
using std::endl;
6
7
8
9
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
#include <iterator> // ostream_iterator
139
Outline
Fig22_27.cpp
(1 of 3)
10
11 int main()
12 {
13
14
const int SIZE = 10;
int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
15
16
17
18
19
20
21
int a2[ SIZE ] = { 1, 2, 3, 4, 1000,
std::vector< int > v1( a1, a1 + SIZE
std::vector< int > v2( a1, a1 + SIZE
std::vector< int > v3( a2, a2 + SIZE
std::ostream_iterator< int > output(
6, 7,
); //
); //
); //
cout,
22
23
std::copy( v1.begin(), v1.end(), output );
cout << "\nVector v2 contains: ";
24
25
26
std::copy( v2.begin(), v2.end(), output );
cout << "\nVector v3 contains: ";
std::copy( v3.begin(), v3.end(), output );
8, 9, 10 };
copy of a1
copy of a1
copy of a2
" " );
cout << "Vector v1 contains: ";
 2008 Pearson Education,
Inc. All rights reserved.
27
28
29
140
// compare vectors v1 and v2 for equality
bool result = std::equal( v1.begin(), v1.end(), v2.begin() );
30
31
32
33
34
cout << "\n\nVector v1 " << ( result ? "is" : "is not" )
<< " equal to vector v2.\n";
35
36
37
cout << "Vector v1 " << ( result ? "is" : "is not" )
<< " equal to vector v3.\n";
38
39
// location represents pair of vector iterators
std::pair< std::vector< int >::iterator,
40
std::vector< int >::iterator > location;
// compare vectors v1 and v3 for equality
result = std::equal( v1.begin(), v1.end(), v3.begin() );
Outline
Compare v1 and v2 for equality
Fig22_27.cpp
(2 of 3)
Compare v1 and v3 for equality
41
42
43
44
45
46
47
// check for mismatch between v1 and v3
location = std::mismatch( v1.begin(), v1.end(), v3.begin() );
cout << "\nThere is a mismatch between v1 and v3 at location "
<< ( location.first - v1.begin() ) << "\nwhere v1 contains "
<< *location.first << " and v3 contains " << *location.second
<< "\n\n";
48
49
50
char c1[ SIZE ] = "HELLO";
char c2[ SIZE ] = "BYE BYE";
Locate the mismatched
elements in v1 and v3
Determine the actual location of
the mismatch relative to the
beginning of the vectors
 2008 Pearson Education,
Inc. All rights reserved.
51
141
52
// perform lexicographical comparison of c1 and c2
53
54
result = std::lexicographical_compare( c1, c1 + SIZE, c2, c2 + SIZE );
cout << c1 << ( result ? " is less than " :
55
56
" is greater than or equal to " )
<< c2 << endl;
return 0;
57 } // end main
Vector v1 contains: 1 2 3 4 5 6 7 8 9 10
Vector v2 contains: 1 2 3 4 5 6 7 8 9 10
Vector v3 contains: 1 2 3 4 1000 6 7 8 9 10
Outline
Compare the contents
of c1 and c2
Fig22_27.cpp
(3 of 3)
Pointers into arrays can be used
as random-access iterators
Vector v1 is equal to vector v2.
Vector v1 is not equal to vector v3.
There is a mismatch between v1 and v3 at location 4
where v1 contains 5 and v3 contains 1000
HELLO is greater than or equal to BYE BYE
 2008 Pearson Education,
Inc. All rights reserved.
22.5.3 remove, remove_if,
remove_copy and remove_copy_if
142
• STL algorithm function remove
– Eliminates all elements with a specified value in a range
• First and second iterator arguments must be at least forward
iterators
• Third argument specifies value to remove
– Does not modify number of elements in the range
• Moves remaining elements toward the beginning of the range
– Returns an iterator positioned after last remaining
element
• Elements after that iterator are undefined
 2008 Pearson Education, Inc. All rights reserved.
22.5.3 remove, remove_if,
remove_copy and remove_copy_if
(Cont.)
143
• STL algorithm function remove_copy
– Copies all elements not having a specified value from one
range to another range
• First and second arguments specify source range
– Must be at least input iterators
• Third argument specifies beginning of destination range
– Must be at least output iterator
• Fourth argument specifies value not to copy
• Returns an iterator positioned after last copied element in
destination range
 2008 Pearson Education, Inc. All rights reserved.
22.5.3 remove, remove_if,
remove_copy and remove_copy_if
(Cont.)
144
• STL algorithm function remove_if
– Eliminates all elements in a range for which a specified
unary predicate function returns true
• First and second iterator arguments must be at least forward
iterators
• Third argument is unary predicate function that takes an
element and returns a bool
– Does not modify number of elements in the range
• Moves remaining elements toward the beginning of the range
– Returns an iterator positioned after last remaining
element
• Elements after that iterator are undefined
 2008 Pearson Education, Inc. All rights reserved.
22.5.3 remove, remove_if,
remove_copy and remove_copy_if
(Cont.)
145
• STL algorithm function remove_copy_if
– Copies all elements for which a specified unary predicate
function does not return true from one range to another
range
• First and second arguments specify source range
– Must be at least input iterators
• Third argument specifies beginning of destination range
– Must be at least output iterator
• Fourth argument is unary predicate function that takes an
element and returns a bool
• Returns an iterator positioned after last copied element in
destination range
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.28: Fig22_28.cpp
2
// Standard Library functions remove, remove_if,
3
// remove_copy and remove_copy_if.
4
5
6
#include <iostream>
using std::cout;
using std::endl;
146
Outline
7
8 #include <algorithm> // algorithm definitions
9 #include <vector> // vector class-template definition
10 #include <iterator> // ostream_iterator
Fig22_28.cpp
(1 of 4)
11
12 bool greater9( int ); // prototype
13
14 int main()
15 {
16
17
18
const int SIZE = 10;
int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };
std::ostream_iterator< int > output( cout, " " );
19
20
21
22
std::vector< int > v( a, a + SIZE ); // copy of a
std::vector< int >::iterator newLastElement;
23
24
25
26
std::copy( v.begin(), v.end(), output );
27
28
cout << "\nVector v after removing all 10s:\n
";
std::copy( v.begin(), newLastElement, output );
cout << "Vector v before removing all 10s:\n
";
// remove all 10s from v
newLastElement = std::remove( v.begin(), v.end(), 10 );
Eliminate all elements
with the value 10 in v
 2008 Pearson Education,
Inc. All rights reserved.
29
30
147
32
33
This vector constructor
receives the
Outline
std::vector< int > c( SIZE, 0 ); // instantiate vector c
number of elements in the vector
cout << "\n\nVector v2 before removing all 10s and copying:\n
";
and
the initial value for those elements
std::copy( v2.begin(), v2.end(), output );
34
35
36
// copy from v2 to c, removing 10s in the process
std::remove_copy( v2.begin(), v2.end(), c.begin(), 10 );
37
cout << "\nVector c after removing all 10s from v2:\n
38
std::copy( c.begin(), c.end(), output );
31
std::vector< int > v2( a, a + SIZE ); // copy of a
Fig22_28.cpp
";
(2 of 4)
Copy all elements that do not have
the value 10 from v2 to c
39
40
41
42
std::vector< int > v3( a, a + SIZE ); // copy of a
cout << "\n\nVector v3 before removing all elements"
<< "\ngreater than 9:\n
";
43
44
45
std::copy( v3.begin(), v3.end(), output );
46
47
48
newLastElement = std::remove_if( v3.begin(), v3.end(), greater9 );
cout << "\nVector v3 after removing all elements"
<< "\ngreater than 9:\n
";
49
50
std::copy( v3.begin(), newLastElement, output );
51
52
std::vector< int > v4( a, a + SIZE ); // copy of a
std::vector< int > c2( SIZE, 0 ); // instantiate vector c2
53
54
55
cout << "\n\nVector v4 before removing all elements"
<< "\ngreater than 9 and copying:\n
";
std::copy( v4.begin(), v4.end(), output );
// remove elements greater than 9 from v3
Delete all elements with values
greater than 9 from v3
 2008 Pearson Education,
Inc. All rights reserved.
56
148
Outline
57
// copy elements from v4 to c2, removing elements greater
58
// than 9 in the process
59
std::remove_copy_if( v4.begin(), v4.end(), c2.begin(), greater9 );
60
cout << "\nVector c2 after removing all elements"
61
<< "\ngreater than 9 from v4:\n
";
62
std::copy( c2.begin(), c2.end(), output );
63
cout << endl;
64
return 0;
Fig22_28.cpp
(3 have
of 4) values
Copy all elements that
not greater than 9 from v4 to c2
65 } // end main
66
67 // determine whether argument is greater than 9
68 bool greater9( int x )
69 {
70
return x > 9;
71 } // end function greater9
 2008 Pearson Education,
Inc. All rights reserved.
Vector v before removing all 10s:
10 2 10 4 16 6 14 8 12 10
Vector v after removing all 10s:
2 4 16 6 14 8 12
Vector v2 before removing all 10s and copying:
10 2 10 4 16 6 14 8 12 10
Vector c after removing all 10s from v2:
2 4 16 6 14 8 12 0 0 0
149
Outline
Fig22_28.cpp
(4 of 4)
Vector v3 before removing all elements
greater than 9:
10 2 10 4 16 6 14 8 12 10
Vector v3 after removing all elements
greater than 9:
2 4 6 8
Vector v4 before removing all elements
greater than 9 and copying:
10 2 10 4 16 6 14 8 12 10
Vector c2 after removing all elements
greater than 9 from v4:
2 4 6 8 0 0 0 0 0 0
 2008 Pearson Education,
Inc. All rights reserved.
22.5.4 replace, replace_if,
replace_copy and replace_copy_if
150
• STL algorithm function replace
– Replaces all elements with a certain value in a range with a
new value
• First and second iterator arguments must be at least forward
iterators
• Third and fourth element arguments specify old value and
new value, respectively
 2008 Pearson Education, Inc. All rights reserved.
22.5.4 replace, replace_if,
replace_copy and replace_copy_if
(Cont.)
151
• STL algorithm function replace_copy
– Copies all elements from one range to another range,
replacing elements with a certain value with a new value
• First and second arguments specify source range
– Must be at least input iterators
• Third argument specifies beginning of destination range
– Must be at least output iterator
• Fourth and fifth element arguments specify old value and
new value, respectively
• Returns an iterator positioned after last copied element in
destination range
 2008 Pearson Education, Inc. All rights reserved.
22.5.4 replace, replace_if,
replace_copy and replace_copy_if
(Cont.)
152
• STL algorithm function replace_if
– Replaces all elements in a range for which a specified
unary predicate function returns true with a new value
• First and second iterator arguments must be at least forward
iterators
• Third argument specifies unary predicate function
• Fourth element argument specifies new value
 2008 Pearson Education, Inc. All rights reserved.
22.5.4 replace, replace_if,
replace_copy and replace_copy_if
(Cont.)
153
• STL algorithm function replace_copy_if
– Copies all elements from one range to another range,
replacing elements for which a unary predicate function
returns true with a new value
• First and second arguments specify source range
– Must be at least input iterators
• Third argument specifies beginning of destination range
– Must be at least output iterator
• Fourth argument specifies unary predicate function
• Fifth argument specifies new value
• Returns an iterator positioned after last copied element in
destination range
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.29: Fig22_29.cpp
2
// Standard Library functions replace, replace_if,
3
// replace_copy and replace_copy_if.
4
#include <iostream>
5
6
using std::cout;
using std::endl;
7
8
9
#include <algorithm>
#include <vector>
154
Outline
Fig22_29.cpp
(1 of 4)
10 #include <iterator> // ostream_iterator
11
12 bool greater9( int ); // predicate function prototype
13
14 int main()
15 {
16
17
18
const int SIZE = 10;
int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };
std::ostream_iterator< int > output( cout, " " );
19
20
std::vector< int > v1( a, a + SIZE ); // copy of a
21
22
cout << "Vector v1 before replacing all 10s:\n
std::copy( v1.begin(), v1.end(), output );
";
Replace all elements with the value
10 in v1 with the new value 100
23
24
25
26
// replace all 10s in v1 with 100
std::replace( v1.begin(), v1.end(), 10, 100 );
cout << "\nVector v1 after replacing 10s with 100s:\n
27
std::copy( v1.begin(), v1.end(), output );
";
 2008 Pearson Education,
Inc. All rights reserved.
28
155
29
std::vector< int > v2( a, a + SIZE ); // copy of a
30
31
std::vector< int > c1( SIZE ); // instantiate vector c1
cout << "\n\nVector v2 before replacing all 10s and copying:\n
32
std::copy( v2.begin(), v2.end(), output );
33
34
35
36
37
// copy from v2 to c1, replacing 10s with 100s
std::replace_copy( v2.begin(), v2.end(), c1.begin(), 10, 100 );
cout << "\nVector c1 after replacing all 10s in v2:\n
";
std::copy( c1.begin(), c1.end(), output );
38
39
40
41
std::vector< int > v3( a, a + SIZE ); // copy of a
cout << "\n\nVector v3 before replacing values greater than
std::copy( v3.begin(), v3.end(), output );
42
43
// replace values greater than 9 in v3 with 100
44
45
std::replace_if( v3.begin(), v3.end(), greater9, 100 );
cout << "\nVector v3 after replacing all values greater"
46
47
48
49
50
<< "\nthan 9 with 100s:\n
";
std::copy( v3.begin(), v3.end(), output );
51
52
53
cout << "\n\nVector v4 before replacing all values greater "
<< "than 9 and copying:\n
";
std::copy( v4.begin(), v4.end(), output );
Outline
";
Fig22_29.cpp
(2 of 4)
Copy all elements in v2 into c1,
replacing all elements with the
10 with the new value 100
9:\n value
";
Replace all elements in v3
that are greater than 9
std::vector< int > v4( a, a + SIZE ); // copy of a
std::vector< int > c2( SIZE ); // instantiate vector c2‘
 2008 Pearson Education,
Inc. All rights reserved.
54
156
55
// copy v4 to c2, replacing elements greater than 9 with 100
56
std::replace_copy_if(
57
v4.begin(), v4.end(), c2.begin(), greater9, 100 );
58
cout << "\nVector c2 after replacing all values greater "
59
<< "than 9 in v4:\n
";
60
std::copy( c2.begin(), c2.end(), output );
61
cout << endl;
62
return 0;
Outline
Copy all elements in v4 into c2,
replacing elements with values
Fig22_29.cpp
greater than 9 with the value 100
(3 of 4)
63 } // end main
64
65 // determine whether argument is greater than 9
66 bool greater9( int x )
67 {
68
return x > 9;
69 } // end function greater9
 2008 Pearson Education,
Inc. All rights reserved.
Vector v1 before replacing all 10s:
10 2 10 4 16 6 14 8 12 10
Vector v1 after replacing 10s with 100s:
100 2 100 4 16 6 14 8 12 100
Vector v2 before replacing all 10s and copying:
10 2 10 4 16 6 14 8 12 10
Vector c1 after replacing all 10s in v2:
100 2 100 4 16 6 14 8 12 100
157
Outline
Fig22_29.cpp
(4 of 4)
Vector v3 before replacing values greater than 9:
10 2 10 4 16 6 14 8 12 10
Vector v3 after replacing all values greater
than 9 with 100s:
100 2 100 4 100 6 100 8 100 100
Vector v4 before replacing all values greater than 9 and copying:
10 2 10 4 16 6 14 8 12 10
Vector c2 after replacing all values greater than 9 in v4:
100 2 100 4 100 6 100 8 100 100
 2008 Pearson Education,
Inc. All rights reserved.
158
22.5.5 Mathematical Algorithms
• STL algorithm function random_shuffle
– Randomly reorders elements in a specified range
• Range specified by two random-access iterator arguments
• STL algorithm function count
– Count number of elements with a specified value in a
specified range
• First and second iterator arguments must be at least input
iterators
• Third argument specifies the element value to count
 2008 Pearson Education, Inc. All rights reserved.
159
22.5.5 Mathematical Algorithms (Cont.)
• STL algorithm function count_if
– Count number of elements for which a unary predicate
function is true in a specified range
• First and second iterator arguments must be at least input
iterators
• Third argument specifies the unary predicate function
• STL algorithm function min_element
– Locate smallest element in a specified range
• First and second iterator arguments must be at least input
iterators
• Returns forward iterator to the smallest element
– Returns the end iterator for the range if it is empty
• Can take third argument to specify a binary function to
compare elements
 2008 Pearson Education, Inc. All rights reserved.
160
22.5.5 Mathematical Algorithms (Cont.)
• STL algorithm function max_element
– Locate largest element in a specified range
• First and second iterator arguments must be at least input
iterators
• Returns forward iterator to the largest element
– Returns the end iterator for the range if it is empty
• Can take third argument to specify a binary function to
compare elements
 2008 Pearson Education, Inc. All rights reserved.
161
22.5.5 Mathematical Algorithms (Cont.)
• STL algorithm function accumulate
– Sums the values in a specified range
• First and second iterator arguments must be at least input
iterators
• Third argument represents the initial value of the total
• Can take fourth argument to specify a general accumulation
function
– Takes two arguments and returns a result
• First argument is the current total
• Second argument is the current element
– Template of accumulate is in header file <numeric>
 2008 Pearson Education, Inc. All rights reserved.
162
22.5.5 Mathematical Algorithms (Cont.)
• STL algorithm function for_each
– Applies a general function to every element in a specified
range
• First and second iterator arguments must be at least input
iterators
• Third argument is the general function
– Takes an element as argument
– Should not modify that element
 2008 Pearson Education, Inc. All rights reserved.
163
22.5.5 Mathematical Algorithms (Cont.)
• STL algorithm function transform
– Applies a general function to every element in a specified
range, storing the results in another range
• First and second iterator arguments must be at least input
iterators
• Third iterator argument specifies the destination range
– Must be at least output iterator
• Fourth argument is the general function
– Takes an element as argument
– Returns the transformed value
– An overloaded version allows elements from two ranges to
be transformed into a third range
• Uses binary general function
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.30: Fig22_30.cpp
2
// Mathematical algorithms of the Standard Library.
3
#include <iostream>
4
5
6
using std::cout;
using std::endl;
7
8
9
10
#include
#include
#include
#include
164
Outline
Fig22_30.cpp
<algorithm> // algorithm definitions
<numeric> // accumulate is defined here
<vector>
<iterator>
(1 of 4)
11
12 bool greater9( int ); // predicate function prototype
13 void outputSquare( int ); // output square of a value
14 int calculateCube( int ); // calculate cube of a value
15
16 int main()
17 {
18
const int SIZE = 10;
19
20
21
22
int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector< int > v( a1, a1 + SIZE ); // copy of a1
std::ostream_iterator< int > output( cout, " " );
23
24
25
26
cout << "Vector v before random_shuffle: ";
std::copy( v.begin(), v.end(), output );
27
28
cout << "\nVector v after random_shuffle: ";
std::copy( v.begin(), v.end(), output );
Randomly reorder the elements in v
std::random_shuffle( v.begin(), v.end() ); // shuffle elements of v
 2008 Pearson Education,
Inc. All rights reserved.
29
30
int a2[ SIZE ] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
31
std::vector< int > v2( a2, a2 + SIZE ); // copy of a2
32
33
cout << "\n\nVector v2 contains: ";
std::copy( v2.begin(), v2.end(), output );
34
35
36
37
// count number of elements in v2 with value 8
int result = std::count( v2.begin(), v2.end(), 8 );
cout << "\nNumber of elements matching 8: " << result;
38
39
40
41
42
// count number of elements in v2 that are greater than 9
result = std::count_if( v2.begin(), v2.end(), greater9 );
cout << "\nNumber of elements greater than 9: " << result;
43
// locate minimum element in v2
44
cout << "\n\nMinimum element in Vector v2 is: "
45
46
<< *( std::min_element( v2.begin(), v2.end() ) );
47
48
49
// locate maximum element in v2
cout << "\nMaximum element in Vector v2 is: "
<< *( std::max_element( v2.begin(), v2.end() ) );
50
51
52
// calculate sum of elements in v
cout << "\n\nThe total of the elements in Vector v is: "
165
Outline
Count the elements with
the value 8 in v2
Fig22_30.cpp
(2 of 4)
Count the elements in v2 whose
values are greater than 9
Locate the smallest element in v2
Locate the largest element in v2
Sum the values in v
<< std::accumulate( v.begin(), v.end(), 0 );
53
54
55
// output square of every element in v
56
57
cout << "\n\nThe square of every integer in Vector v is:\n";
std::for_each( v.begin(), v.end(), outputSquare );
Output the square of
every element in v
 2008 Pearson Education,
Inc. All rights reserved.
58
59
60
std::vector< int > cubes( SIZE ); // instantiate vector cubes
61
// calculate cube of each element in v; place results in cubes
62
std::transform( v.begin(), v.end(), cubes.begin(), calculateCube );
63
cout << "\n\nThe cube of every integer in Vector v is:\n";
64
std::copy( cubes.begin(), cubes.end(), output );
65
cout << endl;
Take
66
return 0;
in
67 } // end main
68
166
Outline
Fig22_30.cpp
(3 of
of every
4)
the cube
element
v and store them in cubes
69 // determine whether argument is greater than 9
70 bool greater9( int value )
71 {
72
return value > 9;
73 } // end function greater9
74
75 // output square of argument
76 void outputSquare( int value )
77 {
78
cout << value * value << ' ';
79 } // end function outputSquare
80
81 // return cube of argument
82 int calculateCube( int value )
83 {
84
return value * value * value;
85 } // end function calculateCube
 2008 Pearson Education,
Inc. All rights reserved.
Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10
Vector v after random_shuffle: 5 4 1 3 7 8 9 10 6 2
Vector v2 contains: 100 2 8 1 50 3 8 8 9 10
Number of elements matching 8: 3
Number of elements greater than 9: 3
Minimum element in Vector v2 is: 1
Maximum element in Vector v2 is: 100
167
Outline
Fig22_30.cpp
(4 of 4)
The total of the elements in Vector v is: 55
The square of every integer in Vector v is:
25 16 1 9 49 64 81 100 36 4
The cube of every integer in Vector v is:
125 64 1 27 343 512 729 1000 216 8
 2008 Pearson Education,
Inc. All rights reserved.
168
Good Programming Practice 22.2
It is a good practice to check that the range
specified in a call to min_element is not empty
and that the return value is not the “past the
end” iterator.
 2008 Pearson Education, Inc. All rights reserved.
22.5.6 Basic Searching and Sorting
Algorithms
169
• STL algorithm function find
– Locates a specified value in a specified range
• First and second iterator arguments must be at least input
iterators
• Returns an input iterator positioned at the first element
containing the value
– Returns an input iterator indicating the end of the range
if the value is not found
 2008 Pearson Education, Inc. All rights reserved.
22.5.6 Basic Searching and Sorting
Algorithms (Cont.)
170
• STL algorithm function find_if
– Locates the first value in a specified range for which a
unary predicate function returns true
• First and second iterator arguments must be at least input
iterators
• Returns an input iterator positioned at the first element for
which the unary predicate function returns true
– Returns an input iterator indicating the end of the range
if no such element is found
 2008 Pearson Education, Inc. All rights reserved.
22.5.6 Basic Searching and Sorting
Algorithms (Cont.)
171
• STL algorithm function sort
– Arranges the elements in a specified range in ascending
order
• First and second iterator arguments must be random-access
iterators
• Can take third argument to specify a binary predicate
function to indicate sorting order
– Takes two element values as arguments
– Returns true if the two elements are in sorted order
 2008 Pearson Education, Inc. All rights reserved.
22.5.6 Basic Searching and Sorting
Algorithms (Cont.)
172
• STL algorithm function binary_search
– Performs a binary search for a specified value in a
specified range
• First and second iterator arguments must be at least forward
iterators
• Third argument specifies value to search for
• Returns a bool indicating whether the value was found
• Can take fourth argument to specify a binary predicate
function to indicate sorting order
– Takes two element values as arguments
– Returns true if the two elements are in sorted order
– Values in the range must be sorted in ascending order first
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.31: Fig22_31.cpp
2
// Standard Library search and sort algorithms.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
6
7
8
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
173
Outline
Fig22_31.cpp
(1 of 3)
9 #include <iterator>
10
11 bool greater10( int value ); // predicate function prototype
12
13 int main()
14 {
15
16
const int SIZE = 10;
int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 };
17
18
std::vector< int > v( a, a + SIZE ); // copy of a
std::ostream_iterator< int > output( cout, " " );
19
20
21
22
23
24
25
26
27
28
29
30
cout << "Vector v contains: ";
std::copy( v.begin(), v.end(), output ); // display output vector
// locate first occurrence of 16 in v
std::vector< int >::iterator location;
location = std::find( v.begin(), v.end(), 16 );
Locate the value 16 in v
if ( location != v.end() ) // found 16
cout << "\n\nFound 16 at location " << ( location - v.begin() );
else // 16 not found
cout << "\n\n16 not found";
 2008 Pearson Education,
Inc. All rights reserved.
31
32
33
174
// locate first occurrence of 100 in v
location = std::find( v.begin(), v.end(), 100 );
Outline
if ( location != v.end() ) // found 100
cout << "\nFound 100 at location " << ( location - v.begin() );
else // 100 not found
cout << "\n100 not found";
Fig22_31.cpp
34
35
36
37
38
39
40
41
42
43
44
// locate first occurrence of value greater than 10 in v
location = std::find_if( v.begin(), v.end(), greater10 );
(2 of 3)
Locate the first value in v
that is greater than 10
if ( location != v.end() ) // found value greater than 10
cout << "\n\nThe first value greater than 10 is " << *location
45
46
47
48
<< "\nfound at location " << ( location - v.begin() );
else // value greater than 10 not found
cout << "\n\nNo values greater than 10 were found";
49
50
51
// sort elements of v
std::sort( v.begin(), v.end() );
cout << "\n\nVector v after sort: ";
52
53
std::copy( v.begin(), v.end(), output );
54
// use binary_search to locate 13 in v
55
if ( std::binary_search( v.begin(), v.end(), 13 ) )
56
57
58
cout << "\n\n13 was found in v";
else
cout << "\n\n13 was not found in v";
Arrange the elements in
v in ascending order
Determine whether the value
13 is in v by performing a
binary search
 2008 Pearson Education,
Inc. All rights reserved.
59
60
// use binary_search to locate 100 in v
61
if ( std::binary_search( v.begin(), v.end(), 100 ) )
62
63
cout << "\n100 was found in v";
else
64
65
66
67
cout << "\n100 was not found in v";
cout << endl;
return 0;
175
Outline
Fig22_31.cpp
(3 of 3)
68 } // end main
69
70 // determine whether argument is greater than 10
71 bool greater10( int value )
72 {
73
return value > 10;
74 } // end function greater10
Vector v contains: 10 2 17 5 16 8 13 11 20 7
Found 16 at location 4
100 not found
The first value greater than 10 is 17
found at location 2
Vector v after sort: 2 5 7 8 10 11 13 16 17 20
13 was found in v
100 was not found in v
 2008 Pearson Education,
Inc. All rights reserved.
176
Common Programming Error 22.5
Attempting to sort a container by using
an iterator other than a random-access
iterator is a compilation error. Function
sort requires a random-access iterator.
 2008 Pearson Education, Inc. All rights reserved.
22.5.7 swap, iter_swap and
swap_ranges
177
• STL algorithm function swap
– Exchange two values for one another
• Takes as arguments two references to values being exchanged
• STL algorithm function iter_swap
– Exchange two values pointed to by iterators for one
another
• Takes as arguments two forward iterators pointing to
elements whose values are being exchanged
 2008 Pearson Education, Inc. All rights reserved.
22.5.7 swap, iter_swap and
swap_ranges (Cont.)
178
• STL algorithm function swap_ranges
– Exchange the elements in two specified ranges
• First and second arguments specify first range
– Must be at least forward iterators
• Third argument specifies beginning of second range
– Must be at least forward iterator
– Specified ranges can be in the same container or two
different containers (or arrays)
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.32: Fig22_32.cpp
2
// Standard Library algorithms iter_swap, swap and swap_ranges.
3
#include <iostream>
4
using std::cout;
5
6
using std::endl;
7
8
#include <algorithm> // algorithm definitions
#include <iterator>
179
Outline
Fig22_32.cpp
(1 of 2)
9
10 int main()
11 {
12
13
const int SIZE = 10;
int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
14
std::ostream_iterator< int > output( cout, " " );
15
16
17
18
cout << "Array a contains:\n
";
std::copy( a, a + SIZE, output ); // display array a
Exchange the first and second
elements of array a
19
20
21
// swap elements at locations 0 and 1 of array a
std::swap( a[ 0 ], a[ 1 ] );
22
cout << "\nArray a after swapping a[0] and a[1] using swap:\n
23
24
25
26
std::copy( a, a + SIZE, output ); // display array a
27
28
cout << "\nArray a after swapping a[0] and a[1] using iter_swap:\n
std::copy( a, a + SIZE, output );
";
// use iterators to swap elements at locations 0 and 1 of array a
std::iter_swap( &a[ 0 ], &a[ 1 ] ); // swap with iterators
";
Treat pointers to the first
and second elements of
array a as iterators
 2008 Pearson Education,
Inc. All rights reserved.
29
180
30
// swap elements in first five elements of array a with
31
// elements in last five elements of array a
32
std::swap_ranges( a, a + 5, a + 5 );
Exchange the first five elements of
a with the next five elements of a
33
34
35
cout << "\nArray a after swapping the first five elements\n"
<< "with the last five elements:\n
36
std::copy( a, a + SIZE, output );
37
cout << endl;
38
return 0;
Outline
Fig22_32.cpp
";
(2 of 2)
39 } // end main
Array a contains:
1 2 3 4 5 6 7 8 9 10
Array a after swapping a[0] and a[1] using swap:
2 1 3 4 5 6 7 8 9 10
Array a after swapping a[0] and a[1] using iter_swap:
1 2 3 4 5 6 7 8 9 10
Array a after swapping the first five elements
with the last five elements:
6 7 8 9 10 1 2 3 4 5
 2008 Pearson Education,
Inc. All rights reserved.
22.5.8 copy_backward, merge, unique
and reverse
181
• STL algorithm function copy_backward
– Copy elements from one specified range to another range
by copying backward
• First and second arguments specify source range
– Must be at least bidirectional iterators
• Third argument points one element past the last element of
destination range
– Must be at least bidirectional iterator
• Begins by copying element before second argument into
element before third argument
– Proceeds backwards from there (toward first argument)
• Returns iterator positioned at last element copied
– The new first element in the destination range
 2008 Pearson Education, Inc. All rights reserved.
22.5.8 copy_backward, merge, unique
and reverse (Cont.)
182
• STL algorithm function merge
– Combines two sorted ascending sequences into a third
sorted sequence
• First and second arguments specify first sequence
– Must be at least input iterators
• Third and fourth arguments specify second sequence
– Must be at least input iterators
• Fifth argument specifies beginning of destination sequence
– Must be at least output iterator
• Can take sixth argument to specify a binary predicate
function that indicates sorting order
– Destination sequence must be at least the combined length
of both source sequences
 2008 Pearson Education, Inc. All rights reserved.
22.5.8 copy_backward, merge, unique
and reverse (Cont.)
183
• Function template back_inserter
– Used when the number of elements to be put into a
container is not known in advance
• Takes container as argument
• Returns an iterator that will call the container’s push_back
function to insert elements
• Thus, container grows in size when necessary
– In header file <iterator>
– In namespace std
– Other inserter function templates
• front_inserter is used to insert at the beginning of the
container
• inserter is used to insert before the element specified in
the second (iterator) argument
 2008 Pearson Education, Inc. All rights reserved.
22.5.8 copy_backward, merge, unique
and reverse (Cont.)
184
• STL algorithm function unique
– Eliminates duplicates in a sorted sequence of elements
• First and second arguments specify sequence
– Must be at least forward iterators
• Can take third argument to specify a binary predicate
function to compare elements for equality
• Returns an iterator positioned after last unique element
– Elements after that iterator are undefined
• STL algorithm function reverse
– Reverses all elements in the specified range
• First and second arguments specify range
– Must be at least bidirectional iterators
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.33: Fig22_33.cpp
// Standard Library functions copy_backward, merge, unique and reverse.
3
#include <iostream>
4
5
using std::cout;
using std::endl;
6
7
8
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
185
Outline
Fig22_33.cpp
(1 of 3)
9 #include <iterator> // ostream_iterator
10
11 int main()
12 {
13
const int SIZE = 5;
14
15
int a1[ SIZE ] = { 1, 3, 5, 7, 9 };
int a2[ SIZE ] = { 2, 4, 5, 7, 9 };
16
17
18
std::vector< int > v1( a1, a1 + SIZE ); // copy of a1
std::vector< int > v2( a2, a2 + SIZE ); // copy of a2
std::ostream_iterator< int > output( cout, " " );
19
20
21
cout << "Vector v1 contains: ";
std::copy( v1.begin(), v1.end(), output ); // display vector output
22
23
cout << "\nVector v2 contains: ";
std::copy( v2.begin(), v2.end(), output ); // display vector outputCopy
24
25
std::vector< int > results( v1.size() );
26
27
28
29
// place elements of v1 into results in reverse order
std::copy_backward( v1.begin(), v1.end(), results.end() );
cout << "\n\nAfter copy_backward, results contains: ";
30
std::copy( results.begin(), results.end(), output );
elements in v1 into results
by starting from the element
before v1.end()and
working toward the beginning
 2008 Pearson Education,
Inc. All rights reserved.
31
32
186
std::vector< int > results2( v1.size() + v2.size() );
Outline
33
34
// merge elements of v1 and v2 into results2 in sorted order
35
std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(),
36
results2.begin() );
37
38
cout << "\n\nAfter merge of v1 and v2 results2 contains:\n";
39
std::copy( results2.begin(), results2.end(), output );
Combine sorted vectors
Fig22_33.cpp
v1 and v2 into sorted
vector
results2
(2 of
3)
40
41
// eliminate duplicate values from results2
42
std::vector< int >::iterator endLocation;
43
endLocation = std::unique( results2.begin(), results2.end() );
44
45
cout << "\n\nAfter unique results2 contains:\n";
46
std::copy( results2.begin(), endLocation, output );
Eliminate duplicate values
from results2
47
48
cout << "\n\nVector v1 after reverse: ";
49
std::reverse( v1.begin(), v1.end() ); // reverse elements of v1
50
std::copy( v1.begin(), v1.end(), output );
51
cout << endl;
52
return 0;
Reverse all elements in v1
53 } // end main
 2008 Pearson Education,
Inc. All rights reserved.
Vector v1 contains: 1 3 5 7 9
Vector v2 contains: 2 4 5 7 9
187
Outline
After copy_backward, results contains: 1 3 5 7 9
After merge of v1 and v2 results2 contains:
1 2 3 4 5 5 7 7 9 9
Fig22_33.cpp
After unique results2 contains:
1 2 3 4 5 7 9
(3 of 3)
Vector v1 after reverse: 9 7 5 3 1
 2008 Pearson Education,
Inc. All rights reserved.
22.5.9 inplace_merge, unique_copy
and reverse_copy
188
• STL algorithm function inplace_merge
– Merges two sorted sequences of elements in the same
container
• First and second arguments specify beginnings of sequences
– Must be at least bidirectional iterators
• Third argument specifies end of the entire sequence
– Must be at least bidirectional iterator
• Can take fourth argument to specify binary predicate
function for comparing elements
 2008 Pearson Education, Inc. All rights reserved.
22.5.9 inplace_merge, unique_copy
and reverse_copy (Cont.)
189
• STL algorithm function unique_copy
– Copies all unique elements in a sorted sequence into
another sequence
• First and second arguments specify source sequence
– Must be at least input iterators
• Third argument specifies beginning of destination sequence
– Must be at least output iterator
• Can take fourth argument to specify binary predicate
function to compare elements for equality
 2008 Pearson Education, Inc. All rights reserved.
22.5.9 inplace_merge, unique_copy
and reverse_copy (Cont.)
190
• STL algorithm function reverse_copy
– Places a reversed copy of the elements in a specified range
in another range
• First and second arguments specify source sequence
– Must be at least bidirectional iterators
• Third argument specifies beginning of destination sequence
– Must be at least output iterator
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.34: Fig22_34.cpp
2
3
4
// Standard Library algorithms inplace_merge,
// reverse_copy and unique_copy.
#include <iostream>
5
using std::cout;
6
7
8
9
using std::endl;
191
Outline
Fig22_34.cpp
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
(1 of 2)
10 #include <iterator> // back_inserter definition
11
12 int main()
13 {
14
const int SIZE = 10;
15
16
17
18
int a1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 };
std::vector< int > v1( a1, a1 + SIZE ); // copy of a
std::ostream_iterator< int > output( cout, " " );
19
20
cout << "Vector v1 contains: ";
std::copy( v1.begin(), v1.end(), output );
21
22
23
// merge first half of v1 with second half of v1 such that
// v1 contains sorted set of elements after merge
24
std::inplace_merge( v1.begin(), v1.begin() + 5, v1.end() );
25
26
cout << "\nAfter inplace_merge, v1 contains: ";
27
std::copy( v1.begin(), v1.end(), output );
28
29
std::vector< int > results1;
Merge the first five elements in v1 with
the remaining five elements in v1
 2008 Pearson Education,
Inc. All rights reserved.
30
31
32
33
// copy only unique elements of v1 into results1
std::unique_copy(
v1.begin(), v1.end(), std::back_inserter( results1 ) );
34
35
cout << "\nAfter unique_copy results1 contains: ";
std::copy( results1.begin(), results1.end(), output );
36
37
std::vector< int > results2;
38
39
// copy elements of v1 into results2 in reverse order
40
41
42
43
44
std::reverse_copy(
v1.begin(), v1.end(), std::back_inserter( results2 ) );
cout << "\nAfter reverse_copy, results2 contains: ";
std::copy( results2.begin(), results2.end(), output );
cout << endl;
45
return 0;
46 } // end main
192
Make a copy ofOutline
all unique elements
in v1 and place the copied
elements in results1
Fig22_34.cpp
Use back_inserter
(2 of 2) to insert
new elements into results1
rather than replace existing
elements
Put a reversed copy of the elements
in v1 into results2
Vector v1 contains: 1 3 5 7 9 1 3 5 7 9
After inplace_merge, v1 contains: 1 1 3 3 5 5 7 7 9 9
After unique_copy results1 contains: 1 3 5 7 9
After reverse_copy, results2 contains: 9 9 7 7 5 5 3 3 1 1
 2008 Pearson Education,
Inc. All rights reserved.
193
22.5.10 Set Operations
• STL algorithm function includes
– Determines whether every element of the second set is in
the first set
• First and second arguments specify first set
– Must be at least input iterators
• Third and fourth arguments specify second set
– Must be at least input iterators
• Both sets must be sorted first
• Can take fifth argument – a binary predicate function to
compare elements for equality
 2008 Pearson Education, Inc. All rights reserved.
194
22.5.10 Set Operations (Cont.)
• STL algorithm function set_difference
– Finds the elements from the first set that are not in the
second set
• First and second arguments specify first set
– Must be at least input iterators
• Third and fourth arguments specify second set
– Must be at least input iterators
• Both sets must be sorted (with same comparison function)
• Fifth argument specifies beginning of set that will store
elements that are in first set but not in second set
– Must be at least output iterator
• Returns output iterator positioned after last copied value
• Can take sixth argument – binary predicate function
indicating original sorting order
 2008 Pearson Education, Inc. All rights reserved.
195
22.5.10 Set Operations (Cont.)
• STL algorithm function intersection
– Finds the elements in both the first set and the second set
• First and second arguments specify first set
– Must be at least input iterators
• Third and fourth arguments specify second set
– Must be at least input iterators
• Both sets must be sorted (with same comparison function)
• Fifth argument specifies beginning of set that will store
elements that are common to both sets
– Must be at least output iterator
• Returns output iterator positioned after last copied value
• Can take sixth argument – binary predicate function
indicating original sorting order
 2008 Pearson Education, Inc. All rights reserved.
196
22.5.10 Set Operations (Cont.)
• STL algorithm function
set_symmetric_difference
– Finds elements in first set that are not in second set or in
second set but not in first set
• First and second arguments specify first set
– Must be at least input iterators
• Third and fourth arguments specify second set
– Must be at least input iterators
• Both sets must be sorted (with same comparison function)
• Fifth argument specifies beginning of set that will store
elements in only one of the two sets
– Must be at least output iterator
• Returns output iterator positioned after last copied value
• Can take sixth argument – binary predicate function
indicating original sorting order
 2008 Pearson Education, Inc. All rights reserved.
197
22.5.10 Set Operations (Cont.)
• STL algorithm function union
– Create a set of all elements in either the first set or the
second set, or both
• First and second arguments specify first set
– Must be at least input iterators
• Third and fourth arguments specify second set
– Must be at least input iterators
• Both sets must be sorted (with same comparison function)
• Fifth argument specifies beginning of set that will store
elements found in either set or both sets
– Must be at least output iterator
• Returns output iterator positioned after last copied value
• Can take sixth argument – binary predicate function
indicating original sorting order
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.35: Fig22_35.cpp
// Standard Library algorithms includes, set_difference,
3
// set_intersection, set_symmetric_difference and set_union.
4
5
#include <iostream>
using std::cout;
6
7
8
using std::endl;
#include <algorithm> // algorithm definitions
9 #include <iterator> // ostream_iterator
10
198
Outline
Fig22_35.cpp
(1 of 3)
11 int main()
12 {
13
const int SIZE1 = 10, SIZE2 = 5, SIZE3 = 20;
14
15
int a1[ SIZE1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int a2[ SIZE2 ] = { 4, 5, 6, 7, 8 };
16
17
18
int a3[ SIZE2 ] = { 4, 5, 6, 11, 15 };
std::ostream_iterator< int > output( cout, " " );
19
20
21
cout << "a1 contains: ";
std::copy( a1, a1 + SIZE1, output ); // display array a1
cout << "\na2 contains: ";
22
23
std::copy( a2, a2 + SIZE2, output ); // display array a2
cout << "\na3 contains: ";
24
25
std::copy( a3, a3 + SIZE2, output ); // display array a3
26
// determine whether set a2 is completely contained in a1
27
28
29
if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) )
cout << "\n\na1 includes a2";
else
30
Determine whether every element
in a2 is contained in a1
cout << "\n\na1 does not include a2";
 2008 Pearson Education,
Inc. All rights reserved.
31
32
33
// determine whether set a3 is completely contained in a1
if ( std::includes( a1, a1 + SIZE1, a3, a3 + SIZE2 ) )
34
35
36
37
38
cout << "\na1 includes a3";
else
cout << "\na1 does not include a3";
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
int difference[ SIZE1 ];
// determine elements of a1 not in a2
int *ptr = std::set_difference( a1, a1 + SIZE1,
a2, a2 + SIZE2, difference );
cout << "\n\nset_difference of a1 and a2 is: ";
std::copy( difference, ptr, output );
199
Outline
Fig22_35.cpp
(2 of 3)
Copy the elements in a1 that are
not in a2 into difference
int intersection[ SIZE1 ];
// determine elements in both a1 and a2
ptr = std::set_intersection( a1, a1 + SIZE1,
a2, a2 + SIZE2, intersection );
cout << "\n\nset_intersection of a1 and a2 is: ";
std::copy( intersection, ptr, output );
Store the elements common to both
a1 and a2 in intersection
int symmetric_difference[ SIZE1 + SIZE2 ];
 2008 Pearson Education,
Inc. All rights reserved.
55
200
56
// determine elements of a1 that are not in a2 and
57
// elements of a2 that are not in a1
58
ptr = std::set_symmetric_difference( a1, a1 + SIZE1,
59
a3, a3 + SIZE2, symmetric_difference );
60
cout << "\n\nset_symmetric_difference of a1 and a3 is: ";
61
std::copy( symmetric_difference, ptr, output );
62
63
Outline
Copy the elements in a1
that are not in a3
Fig22_35.cpp
and the elements in a3 that are not in
a1 into symmetric_difference
(3 of 3)
int unionSet[ SIZE3 ];
64
65
// determine elements that are in either or both sets
66
ptr = std::set_union( a1, a1 + SIZE1, a3, a3 + SIZE2, unionSet );
67
cout << "\n\nset_union of a1 and a3 is: ";
68
std::copy( unionSet, ptr, output );
69
cout << endl;
70
return 0;
71 } // end main
Place the combined set of all elements
in a1 or a3 into unionSet
a1 contains: 1 2 3 4 5 6 7 8 9 10
a2 contains: 4 5 6 7 8
a3 contains: 4 5 6 11 15
a1 includes a2
a1 does not include a3
set_difference of a1 and a2 is: 1 2 3 9 10
set_intersection of a1 and a2 is: 4 5 6 7 8
set_symmetric_difference of a1 and a3 is: 1 2 3 7 8 9 10 11 15
set_union of a1 and a3 is: 1 2 3 4 5 6 7 8 9 10 11 15
 2008 Pearson Education,
Inc. All rights reserved.
22.5.11 lower_bound, upper_bound and
equal_range
201
• STL algorithm function lower_bound
– Find first location in a sorted sequence where a specified
value could be inserted while maintaining sorted order
• First and second arguments specify the sorted sequence
– Must be at least forward iterators
• Third argument is the value to consider inserting
• Returns forward iterator to the lower bound location
• Can take fourth argument – a binary predicate function to
indicate original sorting order
 2008 Pearson Education, Inc. All rights reserved.
22.5.11 lower_bound, upper_bound and
equal_range (Cont.)
202
• STL algorithm function upper_bound
– Find last location in a sorted sequence where a specified
value could be inserted while maintaining sorted order
• First and second arguments specify the sorted sequence
– Must be at least forward iterators
• Third argument is the value to consider inserting
• Returns forward iterator to the upper bound location
• Can take fourth argument – a binary predicate function to
indicate original sorting order
 2008 Pearson Education, Inc. All rights reserved.
22.5.11 lower_bound, upper_bound and
equal_range (Cont.)
203
• STL algorithm function equal_range
– Returns pair of forward iterators containing results of
both lower_bound and upper_bound operations
• First and second arguments specify the sorted sequence
– Must be at least forward iterators
• Third argument is the value to consider inserting
• Returns pair of forward iterators (lower bound in first,
upper bound in second)
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.36: Fig22_36.cpp
// Standard Library functions lower_bound, upper_bound and
3
// equal_range for a sorted sequence of values.
4
5
#include <iostream>
using std::cout;
6
using std::endl;
7
8
9
#include <algorithm> // algorithm definitions
#include <vector> // vector class-template definition
204
Outline
Fig22_36.cpp
(1 of 4)
10 #include <iterator> // ostream_iterator
11
12 int main()
13 {
14
const int SIZE = 10;
15
16
17
18
19
20
21
int a1[ SIZE ] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 };
std::vector< int > v( a1, a1 + SIZE ); // copy of a1
std::ostream_iterator< int > output( cout, " " );
22
23
// determine lower-bound insertion point for 6 in v
std::vector< int >::iterator lower;
24
25
26
lower = std::lower_bound( v.begin(), v.end(), 6 );
cout << "\n\nLower bound of 6 is element "
<< ( lower - v.begin() ) << " of vector v";
cout << "Vector v contains:\n";
std::copy( v.begin(), v.end(), output );
Find the first location where 6 can be
inserted in sorted order into vector v
Calculate the lower-bound position
relative to the beginning of v
 2008 Pearson Education,
Inc. All rights reserved.
27
205
28
// determine upper-bound insertion point for 6 in v
29
30
31
32
33
34
35
36
std::vector< int >::iterator upper;
upper = std::upper_bound( v.begin(), v.end(), 6 );
cout << "\nUpper bound of 6 is element "
<< ( upper - v.begin() ) << " of vector v";
37
38
std::vector< int >::iterator > eq;
eq = std::equal_range( v.begin(), v.end(), 6 );
39
40
cout << "\nUsing equal_range:\n
Lower bound of 6 is element "
<< ( eq.first - v.begin() ) << " of vector v";
41
42
cout << "\n
Upper bound of 6 is element "
<< ( eq.second - v.begin() ) << " of vector v";
43
44
45
46
47
cout << "\n\nUse lower_bound to locate the first point\n"
<< "at which 5 can be inserted in order";
48
49
50
51
cout << "\n
Lower bound of 5 is element "
<< ( lower - v.begin() ) << " of vector v";
cout << "\n\nUse upper_bound to locate the last point\n"
<< "at which 7 can be inserted in order";
// use equal_range to determine both the lower- and
// upper-bound insertion points for 6
std::pair< std::vector< int >::iterator,
Outline
Find the last location where 6 can be
inserted in sorted order in vector v
Fig22_36.cpp
(2 of 4)
Find the lower bound and upper bound for 6
in v using the equal_range algorithm
// determine lower-bound insertion point for 5 in v
lower = std::lower_bound( v.begin(), v.end(), 5 );
 2008 Pearson Education,
Inc. All rights reserved.
52
206
53
// determine upper-bound insertion point for 7 in v
54
upper = std::upper_bound( v.begin(), v.end(), 7 );
55
cout << "\n
56
Upper bound of 7 is element "
<< ( upper - v.begin() ) << " of vector v";
57
cout << "\n\nUse equal_range to locate the first and\n"
58
<< "last point at which 5 can be inserted in order";
60
// use equal_range to determine both the lower- and
61
// upper-bound insertion points for 5
62
eq = std::equal_range( v.begin(), v.end(), 5 );
63
cout << "\n
65
66
67
Fig22_36.cpp
(3 of 4)
59
64
Outline
Lower bound of 5 is element "
<< ( eq.first - v.begin() ) << " of vector v";
cout << "\n
Upper bound of 5 is element "
<< ( eq.second - v.begin() ) << " of vector v" << endl;
return 0;
68 } // end main
 2008 Pearson Education,
Inc. All rights reserved.
207
Vector v contains:
2 2 4 4 4 6 6 6 6 8
Lower bound of 6 is
Upper bound of 6 is
Using equal_range:
Lower bound of 6
Upper bound of 6
Outline
element 5 of vector v
element 9 of vector v
is element 5 of vector v
is element 9 of vector v
Use lower_bound to locate the first point
at which 5 can be inserted in order
Lower bound of 5 is element 5 of vector v
Fig22_36.cpp
(4 of 4)
Use upper_bound to locate the last point
at which 7 can be inserted in order
Upper bound of 7 is element 9 of vector v
Use equal_range to locate the first and
last point at which 5 can be inserted in order
Lower bound of 5 is element 5 of vector v
Upper bound of 5 is element 5 of vector v
 2008 Pearson Education,
Inc. All rights reserved.
208
22.5.12 Heapsort
• Heapsort sorting algorithm
– Heap
• A special binary tree
• Stored as an array of elements
• Key feature
– Largest element is always at top
– Values of children nodes are always less than or equal to
parent node’s value
– Often called a maxheap
 2008 Pearson Education, Inc. All rights reserved.
209
22.5.12 Heapsort (Cont.)
• STL algorithm function make_heap
– Arranges a sequence of values into a heap
• First and second arguments specify the sequence
– Must be random-access iterators
• Can take third argument – a binary predicate function for
comparing values
• STL algorithm function sort_heap
– Sorts a sequence of values that is already in a heap
• First and second arguments specify the sequence
– Must be random-access iterators
• Can take third argument – a binary predicate function for
comparing values
 2008 Pearson Education, Inc. All rights reserved.
210
22.5.12 Heapsort (Cont.)
• STL algorithm function push_heap
– Adds a new value into a heap
• First and second arguments specify the sequence
– Must be random-access iterators
• Can take third argument – a binary predicate function for
comparing values
– Assumes that
• last element in the sequence is value being added to the heap
• All elements before last element are arranged as a heap
 2008 Pearson Education, Inc. All rights reserved.
211
22.5.12 Heapsort (Cont.)
• STL algorithm function push_heap
– Adds a new value into a heap
• First and second arguments specify the sequence
– Must be random-access iterators
• Can take third argument – a binary predicate function for
comparing values
– Assumes that
• last element in the sequence is value being added to the heap
• All elements before last element are arranged as a heap
 2008 Pearson Education, Inc. All rights reserved.
212
22.5.12 Heapsort (Cont.)
• STL algorithm function pop_heap
– Removes the top element in a heap
• First and second arguments specify the sequence
– Must be random-access iterators
• Can take third argument – a binary predicate function for
comparing values
– Assumes that sequence elements are arranged as a heap
– Swaps top heap element with last element in sequence
• Then rearranges remaining heap elements into a new heap
– Repeatedly removing top element of the remaining heap
results in a sorted sequence in the original container area
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.37: Fig22_37.cpp
2
3
4
// Standard Library algorithms push_heap, pop_heap,
// make_heap and sort_heap.
#include <iostream>
5
using std::cout;
6
7
8
9
using std::endl;
#include <algorithm>
#include <vector>
213
Outline
Fig22_37.cpp
(1 of 4)
10 #include <iterator>
11
12 int main()
13 {
14
const int SIZE = 10;
15
16
17
18
int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };
std::vector< int > v( a, a + SIZE ); // copy of a
std::vector< int > v2;
std::ostream_iterator< int > output( cout, " " );
19
20
cout << "Vector v before make_heap:\n";
21
22
23
std::copy( v.begin(), v.end(), output );
24
cout << "\nVector v after make_heap:\n";
25
26
std::copy( v.begin(), v.end(), output );
27
std::sort_heap( v.begin(), v.end() ); // sort elements with sort_heap
28
29
cout << "\nVector v after sort_heap:\n";
std::copy( v.begin(), v.end(), output );
Arrange the elements
of v into a heap
std::make_heap( v.begin(), v.end() ); // create heap from vector v
Sort the elements of
v using heapsort
 2008 Pearson Education,
Inc. All rights reserved.
30
31
// perform the heapsort with push_heap and pop_heap
32
cout << "\n\nArray a contains: ";
33
std::copy( a, a + SIZE, output ); // display array a
34
cout << endl;
214
Outline
35
Fig22_37.cpp
36
37
// place elements of array a into v2 and
// maintain elements of v2 in heap
38
39
40
41
42
for ( int i = 0; i < SIZE; i++ )
Insert value a[ i
{
v2.push_back( a[ i ] );
Push value a[
std::push_heap( v2.begin(), v2.end() );
cout << "\nv2 after push_heap(a[" << i << "]): ";
43
44
45
46
47
48
49
50
51
52
53
std::copy( v2.begin(), v2.end(), output );
} // end for
(2 of 4)
] into v2
i ] into the heap in v2
cout << endl;
// remove elements from heap in sorted order
for ( unsigned int j = 0; j < v2.size(); j++ )
{
cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";
std::pop_heap( v2.begin(), v2.end() - j );
Remove
std::copy( v2.begin(), v2.end(), output );
54
} // end for
55
56
cout << endl;
57
return 0;
58 } // end main
the top heap element and place
it in the jth-to-last position in v2
 2008 Pearson Education,
Inc. All rights reserved.
215
Vector v before make_heap:
3 100 52 77 22 31 1 98 13 40
Vector v after make_heap:
100 98 52 77 40 31 1 3 13 22
Vector v after sort_heap:
1 3 13 22 31 40 52 77 98 100
Outline
Fig22_37.cpp
Array a contains: 3 100 52 77 22 31 1 98 13 40
(3 of 4)
v2
v2
v2
v2
v2
v2
v2
v2
v2
v2
after
after
after
after
after
after
after
after
after
after
push_heap(a[0]):
push_heap(a[1]):
push_heap(a[2]):
push_heap(a[3]):
push_heap(a[4]):
push_heap(a[5]):
push_heap(a[6]):
push_heap(a[7]):
push_heap(a[8]):
push_heap(a[9]):
3
100
100
100
100
100
100
100
100
100
3
3 52
77 52
77 52
77 52
77 52
98 52
98 52
98 52
3
3 22
3 22 31
3 22 31 1
77 22 31 1 3
77 22 31 1 3 13
77 40 31 1 3 13 22
(continued at the top of next slide...)
 2008 Pearson Education,
Inc. All rights reserved.
(...continued from bottom of previous slide )
v2 after 100 popped from heap
98 77 52 22 40 31 1 3 13 100
v2 after 98 popped from heap
77 40 52 22 13 31 1 3 98 100
v2 after 77 popped from heap
52 40 31 22 13 3 1 77 98 100
v2 after 52 popped from heap
40 22 31 1 13 3 52 77 98 100
v2 after 40 popped from heap
31 22 3 1 13 40 52 77 98 100
v2 after 31 popped from heap
22 13 3 1 31 40 52 77 98 100
v2 after 22 popped from heap
13 1 3 22 31 40 52 77 98 100
v2 after 13 popped from heap
3 1 13 22 31 40 52 77 98 100
v2 after 3 popped from heap
1 3 13 22 31 40 52 77 98 100
v2 after 1 popped from heap
1 3 13 22 31 40 52 77 98 100
216
Outline
Fig22_37.cpp
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
217
22.5.13 min and max
• STL algorithm function min
– Returns the smaller of two elements
• STL algorithm function max
– Returns the larger of two elements
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.38: Fig22_38.cpp
2
// Standard Library algorithms min and max.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
218
Outline
Fig22_38.cpp
6
7
#include <algorithm>
8
9
Determine which of 12 and(17ofis 1)
smaller
int main()
Determine which of 12 and 7 is larger
10 {
11
cout << "The minimum of 12 and 7 is: " << std::min( 12, 7 );
12
cout << "\nThe maximum of 12 and 7 is: " << std::max( 12, 7 );
13
cout << "\nThe minimum of 'G' and 'Z' is: " << std::min( 'G', 'Z' );
14
cout << "\nThe maximum of 'G' and 'Z' is: " << std::max( 'G', 'Z' );
15
cout << endl;
16
return 0;
Determine which of 'G' and 'Z' is less
17 } // end main
The
The
The
The
minimum
maximum
minimum
maximum
of
of
of
of
12 and 7 is: 7
12 and 7 is: 12
'G' and 'Z' is: G
'G' and 'Z' is: Z
Determine which of 'G' and 'Z' is greater
 2008 Pearson Education,
Inc. All rights reserved.
219
Algorithm
Description
inner_product
Calculate the sum of the products of two sequences by taking
corresponding elements in each sequence, multiplying those
elements and adding the result to a total.
adjacent_difference
Beginning with the second element in a sequence, calculate
the difference (using operator –) between the current and
previous elements, and store the result. The first two input
iterator arguments indicate the range of elements in the
container and the third indicates where the results should be
stored. A second version of this algorithm takes as a fourth
argument a binary function to perform a calculation
between the current element and the previous element.
partial_sum
Calculate a running total (using operator +) of the values in
a sequence. The first two input iterator arguments indicate
the range of elements in the container and the third indicates
where the results should be stored. A second version of this
algorithm takes as a fourth argument a binary function that
performs a calculation between the current value in the
sequence and the running total.
Fig. 22.39 | Algorithms not covered in this chapter. (Part 1 of 5)
 2008 Pearson Education, Inc. All rights reserved.
220
Algorithm
Description
nth_element
Use three random-access iterators to partition a range of
elements. The first and last arguments represent the range of
elements. The second argument is the partitioning element’s
location. After this algorithm executes, all elements before the
partitioning element are less than that element and all elements
after the partitioning element are greater than or equal to that
element. A second version of this algorithm takes as a fourth
argument a binary comparison function.
partition
This algorithm is similar to nth_element, but it requires less
powerful bidirectional iterators, making it more flexible than
nth_element. Algorithm partition requires two
bidirectional iterators indicating the range of elements to
partition. The third element is a unary predicate function that
helps partition the elements so that all elements in the sequence
for which the predicate is true are to the left (toward the
beginning of the sequence) of all elements for which the predicate
is false. A bidirectional iterator is returned indicating the first
element in the sequence for which the predicate returns false.
Fig. 22.39 | Algorithms not covered in this chapter. (Part 2 of 5)
 2008 Pearson Education, Inc. All rights reserved.
221
Algorithm
Description
stable_partition
This algorithm is similar to partition except that
elements for which the predicate function returns true
are maintained in their original order and elements for
which the predicate function returns false are
maintained in their original order.
Next lexicographical permutation of a sequence.
Previous lexicographical permutation of a sequence.
Use three forward iterator arguments to rotate the
sequence indicated by the first and last argument by the
number of positions indicated by subtracting the first
argument from the second argument. For example, the
sequence 1, 2, 3, 4, 5 rotated by two positions would be 4, 5,
1, 2, 3.
This algorithm is identical to rotate except that the
results are stored in a separate sequence indicated by the
fourth argument—an output iterator. The two sequences
must have the same number of elements.
This algorithm returns an input iterator indicating the first
of two identical adjacent elements in a sequence. If there
are no identical adjacent elements, the iterator is
positioned at the end of the sequence.
next_permutation
prev_permutation
rotate
rotate_copy
adjacent_find
Fig. 22.39 | Algorithms not covered in this chapter. (Part 3 of 5)
 2008 Pearson Education, Inc. All rights reserved.
222
Algorithm
Description
search
This algorithm searches for a subsequence of elements within a
sequence of elements and, if such a subsequence is found,
returns a forward iterator that indicates the first element of
that subsequence. If there are no matches, the iterator is
positioned at the end of the sequence to be searched.
search_n
This algorithm searches a sequence of elements looking for a
subsequence in which the values of a specified number of
elements have a particular value and, if such a subsequence is
found, returns a forward iterator that indicates the first element
of that subsequence. If there are no matches, the iterator is
positioned at the end of the sequence to be searched.
partial_sort
Use three random-access iterators to sort part of a sequence.
The first and last arguments indicate the sequence of elements.
The second argument indicates the ending location for the
sorted part of the sequence. By default, elements are ordered
using operator < (a binary predicate function can also be
supplied). The elements from the second argument iterator to
the end of the sequence are in an undefined order.
Fig. 22.39 | Algorithms not covered in this chapter. (Part 4 of 5)
 2008 Pearson Education, Inc. All rights reserved.
223
Algorithm
Description
partial_sort_copy
Use two input iterators and two random-access iterators
to sort part of the sequence indicated by the two input
iterator arguments. The results are stored in the sequence
indicated by the two random-access iterator arguments.
By default, elements are ordered using operator < (a
binary predicate function can also be supplied). The
number of elements sorted is the smaller of the number of
elements in the result and the number of elements in the
original sequence.
stable_sort
The algorithm is similar to sort except that all equal
elements are maintained in their original order.
Fig. 22.39 | Algorithms not covered in this chapter. (Part 5 of 5)
 2008 Pearson Education, Inc. All rights reserved.
224
22.6 Class bitset
• Class bitset
– Create and manipulate bit sets
• Useful for representing sets of bit flags
– Fixed in size at compile time
– Example
• bitset< size > b;
– Creates bitset b
• Contains size number of bits, all initially 0
– Member function set
• Sets a specified bit to “on”
• Sets all bits to “on” if no argument is specified
 2008 Pearson Education, Inc. All rights reserved.
225
22.6 Class bitset (Cont.)
• Class bitset (Cont.)
– Member function reset
• Sets a specified bit to “off”
• Sets all bits to “off” if no argument is specified
– Member function flip
• “Flips” a specified bit (on changes to off, off changes to on)
• Flips all bits if no argument is specified
– Subscript operator []
• Returns a reference to a specified bit
 2008 Pearson Education, Inc. All rights reserved.
226
22.6 Class bitset (Cont.)
• Class bitset (Cont.)
– Member function at
• Returns a reference to a specified bit
• Performs range-checking
– Throws an out_of_range exception
– Member function test
• Returns true if a specified bit is on or false if it is off
• Performs range-checking
– Throws an out_of_range exception
– Member function size
• Returns the number of bits in the bitset
 2008 Pearson Education, Inc. All rights reserved.
227
22.6 Class bitset (Cont.)
• Class bitset (Cont.)
– Member function count
• Returns the number of bits that are set in the bitset
– Member function any
• Returns true if any bit is set in the bitset
– Member function none
• Returns true if none of the bits is set in the bitset
– Equality operator == and inequality operator !=
• Compare two bitsets for equality and inequality,
respectively
 2008 Pearson Education, Inc. All rights reserved.
228
22.6 Class bitset (Cont.)
• Class bitset (Cont.)
– Bitwise assignment operator &=, |= and ^=
• Used to combine bitsets
– Bit-by-bit logical AND with &=
– Bit-by-bit logical OR with |=
– Bit-by-bit logical XOR with ^=
– Bitwise shift operators >>= and <<=
• Shift the bits in a bitset to the right and left, respectively
– Member functions to_string and to_ulong
• Convert the bitset to a string and an unsigned long,
respectively
 2008 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 22.40: Fig22_40.cpp
// Using a bitset to demonstrate the Sieve of Eratosthenes.
3
#include <iostream>
4
5
using std::cin;
using std::cout;
6
using std::endl;
7
8
9
#include <iomanip>
using std::setw;
229
Outline
Fig22_40.cpp
(1 of 4)
10
11 #include <cmath>
12 using std::sqrt; // sqrt prototype
13
14 #include <bitset> // bitset class definition
15
16 int main()
17 {
18
const int SIZE = 1024;
19
int value;
20
std::bitset< SIZE > sieve; // create bitset of 1024 bits
21
sieve.flip(); // flip all bits in bitset sieve
Create a bitset of 1024 bits,
all set to “off” by default
Flip all bits to “on”
22
23
sieve.reset( 0 ); // reset first bit (number 0)
sieve.reset( 1 ); // reset second bit (number 1)
24
25
26
// perform Sieve of Eratosthenes
int finalBit = sqrt( static_cast< double > ( sieve.size() ) ) + 1;
0 and 1 are not prime numbers
Determine when the algorithm should terminate
 2008 Pearson Education,
Inc. All rights reserved.
27
28
// determine all prime numbers from 2 to 1024
29
for ( int i = 2; i < finalBit; i++ )
30
{
31
32
33
34
35
36
37
38
if ( sieve.test( i ) ) // bit i is on
{
for ( int j = 2 * i; j < SIZE; j += i )
sieve.reset( j ); // set bit j off
} // end if
} // end for
Fig22_40.cpp
(2 of 4)
All numbers that are multiples
of i are not prime numbers
cout << "The prime numbers in the range 2 to 1023 are:\n";
// display prime numbers in range 2-1023
41
42
for ( int k = 2, counter = 1; k < SIZE; k++ )
{
45
46
47
Outline
If i is a prime number
39
40
43
44
230
Check if k is a prime number
if ( sieve.test( k ) ) // bit k is on
{
cout << setw( 5 ) << k;
if ( counter++ % 12 == 0 ) // counter is a multiple of 12
cout << '\n';
} // end if
} // end for
48
49
50
51
52
cout << endl;
53
54
55
56
// get value from user to determine whether value is prime
cout << "\nEnter a value from 2 to 1023 (-1 to end): ";
cin >> value;
 2008 Pearson Education,
Inc. All rights reserved.
57
231
58
// determine whether user input is prime
59
while ( value != -1 )
60
{
61
62
63
64
Outline
Check if value is a prime number
if ( sieve[ value ] ) // prime number
cout << value << " is a prime number\n";
Fig22_40.cpp
else // not a prime number
cout << value << " is not a prime number\n";
(3 of 4)
65
66
cout << "\nEnter a value from 2 to 1023 (-1 to end): ";
67
cin >> value;
68
} // end while
69
70
return 0;
71 } // end main
 2008 Pearson Education,
Inc. All rights reserved.
The prime numbers in the range 2 to 1023 are:
2
3
5
7
11
13
17
19
23
41
43
47
53
59
61
67
71
73
97 101 103 107 109 113 127 131 137
157 163 167 173 179 181 191 193 197
227 229 233 239 241 251 257 263 269
283 293 307 311 313 317 331 337 347
367 373 379 383 389 397 401 409 419
439 443 449 457 461 463 467 479 487
509 521 523 541 547 557 563 569 571
599 601 607 613 617 619 631 641 643
661 673 677 683 691 701 709 719 727
751 757 761 769 773 787 797 809 811
829 839 853 857 859 863 877 881 883
919 929 937 941 947 953 967 971 977
1009 1013 1019 1021
232
29
79
139
199
271
349
421
491
577
647
733
821
887
983
31
83
149
211
277
353
431
499
587
653
739
823
907
991
37
89
151
223
281
359
433
503
593
659
743
827
911
997
Outline
Fig22_40.cpp
(4 of 4)
Enter a value from 2 to 1023 (-1 to end): 389
389 is a prime number
Enter a value from 2 to 1023 (-1 to end): 88
88 is not a prime number
Enter a value from 2 to 1023 (-1 to end): -1
 2008 Pearson Education,
Inc. All rights reserved.
233
22.7 Function Objects
• Function object
– An object of a class that overloads the parentheses
operator
• With a function named operator()
– Can be used syntactically and semantically like a function
or function pointer
• Can be passed to an STL algorithm that takes a function
pointer
– Advantages over function pointers
• Overloaded operator() can be inlined to improve
performance
• Can utilize class data members in performing tasks
– Many predefined function objects are in <functional>
 2008 Pearson Education, Inc. All rights reserved.
234
STL function objects
Type
STL function objects
Type
divides< T >
arithmetic
logical_or< T >
logical
equal_to< T >
relational
minus< T >
arithmetic
greater< T >
relational
modulus< T >
arithmetic
greater_equal< T >
relational
negate< T >
arithmetic
less< T >
relational
not_equal_to< T >
relational
less_equal< T >
relational
plus< T >
arithmetic
logical_and< T >
logical
multiplies< T >
arithmetic
logical_not< T >
logical
Fig. 22.41 | Function objects in the Standard Library
 2008 Pearson Education, Inc. All rights reserved.
1
// Fig. 22.42: Fig22_42.cpp
2
// Demonstrating function objects.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
235
Outline
Fig22_42.cpp
6
7
#include <vector> // vector class-template definition
8
#include <algorithm> // copy algorithm
9
#include <numeric> // accumulate algorithm
(1 of 3)
10 #include <functional> // binary_function definition
11 #include <iterator> // ostream_iterator
12
13 // binary function adds square of its second argument and the
14 // running total in its first argument, then returns the sum
15 int sumSquares( int total, int value )
16 {
17
return total + value * value;
Define function sumSquares
18 } // end function sumSquares
 2008 Pearson Education,
Inc. All rights reserved.
19
20 // binary function class template defines overloaded operator()
21 // that adds the square of its second argument and running
236
Outline
22 // total in its first argument, then returns sum
23
24
25
26
27
28
29
30
template< typename T >
class SumSquaresClass : public std::binary_function< T, T, T >
{
public:
// add square of value to total and return result
T operator()( const T &total, const T &value )
{
return total + value * value;
Fig22_42.cpp
(2 of 3)
Define class SumSquaresClass
which
will be used to instantiate function objects
31
} // end function operator()
32 }; // end class SumSquaresClass
33
34 int main()
35 {
36
const int SIZE = 10;
37
int array[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
38
std::vector< int > integers( array, array + SIZE ); // copy of array
39
std::ostream_iterator< int > output( cout, " " );
40
41
int result;
42
cout << "vector integers contains:\n";
43
std::copy( integers.begin(), integers.end(), output );
44
45
46
// calculate sum of squares of elements of vector integers
// using binary function sumSquares
47
result = std::accumulate( integers.begin(), integers.end(),
48
0, sumSquares );
Pass a pointer to function
sumSquares to accumulate
 2008 Pearson Education,
Inc. All rights reserved.
49
50
51
237
cout << "\n\nSum of squares of elements in integers using "
Outline
<< "binary\nfunction sumSquares: " << result;
52
53
// calculate sum of squares of elements of vector integers
54
// using binary function object
55
result = std::accumulate( integers.begin(), integers.end(),
56
0, SumSquaresClass< int >() );
57
Fig22_42.cpp
(3 of 3)
Pass an instance of class SumSquaresClass
(a function
object) to accumulate
integers using
"
58
cout << "\n\nSum of squares of elements in
59
<< "binary\nfunction object of type "
60
<< "SumSquaresClass< int >: " << result << endl;
61
return 0;
62 } // end main
vector integers contains:
1 2 3 4 5 6 7 8 9 10
Sum of squares of elements in integers using binary
function sumSquares: 385
Sum of squares of elements in integers using binary
function object of type SumSquaresClass< int >: 385
 2008 Pearson Education,
Inc. All rights reserved.
238
22.9 STL Internet and Web Resources
• Tutorials
– www.cs.brown.edu/people/jak/programming/st
l-tutorial/tutorial.html
• STL tutorial organized by examples, philosophy, components
and extending the STL
– www.yrl.co.uk/phil/stl/stl.htmlx
• Function templates, class templates, STL components,
containers, iterators, adaptors and function objects
– www.xraylith.wisc.edu/~khan/software/stl/o
s_examples/examples.html
• Introduction to STL and ObjectSpace STL Tool Kit
 2008 Pearson Education, Inc. All rights reserved.
22.9 STL Internet and Web Resources
(Cont.)
239
• References
– www.sgi.com/tech/stl
• Silicon Graphics STL Programmer’s Guide
– Latest information, design documentation and links
– www.cppreference.com/cpp_stl.html
• Lists constructors, operators and functions for each
container
• Articles, Books and Interviews
– www.byte.com/art/9510/sec12/art3.htm
• Provides information on the use of STL
– www.sgi.com/tech/stl/drdobbsinterview.html
• Interview with Alexander Stepanov, one of the STL creators
 2008 Pearson Education, Inc. All rights reserved.
22.9 STL Internet and Web Resources
(Cont.)
240
• ANSI/ISO C++ Standard
– www.ansi.org
• C++ standard document available for purchase
• Software
– www.cs.rpi.edu/~musser/stl-book
• Information and resources for using STL
– msdn.microsoft.com/visualc
• Microsoft Visual C++ home page – news, updates, technical
resources, samples and downloads
– www.borland.com/cbuilder
• Borland C++Builder home page – newsgroups, product
enhancements, FAQs and more
 2008 Pearson Education, Inc. All rights reserved.