2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

238
2008 Pearson Education, Inc. All rights rese 1 2 2 Standard Template Library (STL)

Transcript of 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

Page 1: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

1

2222Standard Template

Library (STL)

Page 2: 2008 Pearson Education, Inc. All rights reserved. 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

Page 3: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

3

OBJECTIVES

In this chapter you’ll learn: To use the template STL containers, container

adapters and "near containers." 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.

Page 4: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

4

22.1 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

22.2 Sequence Containers

22.2.1 vector Sequence Container

22.2.2 list Sequence Container

22.2.3 deque Sequence Container

22.3 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

22.4 Container Adapters

22.4.1 stack Adapter

22.4.2 queue Adapter

22.4.3 priority_queue Adapter

Page 5: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

5

22.5 Algorithms

22.5.1 fill, fill_n, generate and generate_n22.5.2 equal, mismatch and lexicographical_compare22.5.3 remove, remove_if, remove_copy and

remove_copy_if

22.5.4 replace, replace_if, replace_copy and replace_copy_if22.5.5 Mathematical Algorithms

22.5.6 Basic Searching and Sorting Algorithms

22.5.7 swap, iter_swap and swap_ranges22.5.8 copy_backward, merge, unique and reverse22.5.9 inplace_merge, unique_copy and reverse_copy22.5.10 Set Operations

22.5.11 lower_bound, upper_bound and equal_range22.5.12 Heapsort

22.5.13 min and max22.5.14 STL Algorithms Not Covered in This Chapter

Page 6: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 7: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

7

22.1 Introduction to the Standard Template Library (STL)

• Standard Template Library (STL)– Defines powerful, template-based, reusable components

and algorithms to process them• Implements many common data structures

– Developed by Alexander Stepanov and Meng Lee

– Conceived and designed for performance and flexibility

– Three key components• Containers

• Iterators

• Algorithms

Page 8: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 9: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 10: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

10

22.1 Introduction to the Standard Template Library (STL) (Cont.)

• 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

Page 11: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

11

22.1 Introduction to the Standard Template Library (STL) (Cont.)

• STL iterators– Used to manipulate STL-container elements

• Similar to pointers

– Standard pointers can be used as iterators• So standard arrays can be manipulated as STL containers

Page 12: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

12

22.1 Introduction to the Standard Template Library (STL) (Cont.)

• 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

Page 13: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 14: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 15: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 16: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 17: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

17

Fig. 22.1 | Standard Library container classes.

Standard Library container class

Description

Sequence containers

Vector rapid insertions and deletions at back direct access to any element

deque rapid insertions and deletions at front or back direct access to any element

list doubly linked list, rapid insertion and deletion anywhere

Associative containers

set rapid lookup, no duplicates allowed

multiset rapid lookup, duplicates allowed

map one-to-one mapping, no duplicates allowed, rapid key-based lookup

multimap one-to-many mapping, duplicates allowed, rapid key-based lookup

Container adapters

stack last-in, first-out (LIFO)

queue first-in, first-out (FIFO)

priority_queue highest-priority element is always the first element out

Page 18: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 19: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

19

Fig. 22.2 | STL container common functions. (Part 1 of 2)

Common member functions for all STL containers

Description

default constructor A constructor to provide a default initialization of the container. Normally, each container has several constructors that provide different initialization methods for the container.

copy constructor A constructor that initializes the container to be a copy of an existing container of the same type.

destructor Destructor function for cleanup after a container is no longer needed.

empty Returns true if there are no elements in the container; otherwise, returns false.

insert Inserts an item in the container.

size Returns the number of elements currently in the container.

operator= Assigns one container to another.

operator< Returns true if the first container is less than the second container; otherwise, returns false.

operator<= Returns true if the first container is less than or equal to the second container; otherwise, returns false.

operator> Returns true if the first container is greater than the second container; otherwise, returns false.

operator>= Returns true if the first container is greater than or equal to the second container; otherwise, returns false.

operator== Returns true if the first container is equal to the second container; otherwise, returns false.

operator!= Returns true if the first container is not equal to the second container; otherwise, returns false.

swap Swaps the elements of two containers.

Page 20: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

20

Fig. 22.2 | STL container common functions. (Part 2 of 2)

Common member functions for all STL containers

Description

Functions found only in first-class containers

max_size Returns the maximum number of elements for a container.

begin The two versions of this function return either an iterator or a const_iterator that refers to the first element of the container.

end 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.

rbegin 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.

rend 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.

erase Erases one or more elements from the container.

clear Erases all elements from the container.

Page 21: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

21

Fig. 22.3 | Standard Library container header files.

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.

<valarray>

<bitset>

Page 22: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

22

Fig. 22.4 | typedefs found in first-class containers. (part 1 of 2)

typedef Description

allocator_type The type of the object used to allocate the container’s memory.

value_type The type of element stored in the container.

reference 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.

pointer A pointer to the type of element stored in the container.

const_pointer A pointer to a constant element of the type stored in the container.

iterator An iterator that points to the type of element stored in the container.

const_iterator A constant iterator that points to the type of element stored in the container and can be used only to read elements.

Page 23: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

23

Fig. 22.4 | typedefs found in first-class containers. (part 2 of 2)

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.

const_reverse_iterator 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.

difference_type 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).

size_type The type used to count items in a container and index through a sequence container (cannot index through a list).

Page 24: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 25: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

25

Portability Tip 22.1

Programming with STL will enhance the portability of your code.

Page 26: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 27: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 28: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 29: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 30: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 non-const member functions.

Page 31: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

31 1 // Fig. 22.5: Fig22_05.cpp

2 // Demonstrating input and output with iterators.

3 #include <iostream>

4 using std::cout;

5 using std::cin;

6 using std::endl;

7

8 #include <iterator> // ostream_iterator and istream_iterator

9

10 int main()

11 {

12 cout << "Enter two integers: ";

13

14 // create istream_iterator for reading int values from cin

15 std::istream_iterator< int > inputInt( cin );

16

17 int number1 = *inputInt; // read int from standard input

18 ++inputInt; // move iterator to next input value

19 int number2 = *inputInt; // read int from standard input

20

21 // create ostream_iterator for writing int values to cout

22 std::ostream_iterator< int > outputInt( cout );

23

24 cout << "The sum is: ";

25 *outputInt = number1 + number2; // output result to cout

26 cout << endl;

27 return 0;

28 } // end main

Outline

Fig22_05.cpp

(1 of 2)Create an istream_iterator

capable of extracting int values from standard input cin

Dereference istream_iterator inputInt to read an int from cin

Position 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

Page 32: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

32Outline

Fig22_05.cpp

(2 of 2)

Enter two integers: 12 25

The sum is: 37

Page 33: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 34: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 35: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 in Fig. 22.7

– Iterator category determines what algorithms can be used

Page 36: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

36

Fig. 22.6 | Iterator categories.

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.

output 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.

forward Combines the capabilities of input and output iterators and retains their position in the container (as state information).

bidirectional 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.

random access 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.

Page 37: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

37

Fig. 22.7 | Iterator category hierarchy.

Page 38: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 39: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

39

Fig. 22.8 | Iterator types supported by each Standard Library container.

Container Type of iterator supported

Sequence containers (first class)

vector random access deque random access list bidirectional

Associative containers (first class)

set bidirectional multiset bidirectional map bidirectional multimap bidirectional

Container adapters

stack no iterators supported queue no iterators supported priority_queue no iterators supported

Page 40: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

40

Fig. 22.9 | Iterator typedefs.

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

Page 41: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 42: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

42

Fig. 22.10 | Iterator operations for each type of iterator. (Part 1 of 2 )

Iterator operation Description

All iterators

++p Preincrement an iterator. p++ Postincrement an iterator.

Input iterators

*p Dereference an iterator. p = p1 Assign one iterator to another. p == p1 Compare iterators for equality. p != p1 Compare iterators for inequality.

Output iterators

*p Dereference an iterator. p = p1 Assign one iterator to another.

Forward iterators Forward iterators provide all the functionality of both input iterators and output iterators.

Bidirectional iterators

--p Predecrement an iterator. p-- Postdecrement an iterator.

Page 43: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

43

Fig. 22.10 | Iterator operations for each type of iterator. (Part 2 of 2 )

Iterator operation Description

Random-access iterators

p += i Increment the iterator p by i positions.

p -= i Decrement the iterator p by i positions.

p + i or i + p Expression value is an iterator positioned at p incremented by i positions.

p - i Expression value is an iterator positioned at p decremented by i positions.

p – p1 Expression value is an integer representing the distance between two elements in the same container.

p[ i ] Return a reference to the element offset from p by i positions

p < p1 Return true if iterator p is less than iterator p1 (i.e., iterator p is before iterator p1 in the container); otherwise, return false.

p <= p1 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.

p > p1 Return true if iterator p is greater than iterator p1 (i.e., iterator p is after iterator p1 in the container); otherwise, return false.

p >= p1 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.

Page 44: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 45: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 46: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 47: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 48: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 49: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

49

Fig. 22.11 | Mutating-sequence algorithms.

Mutating-sequence algorithms

copy remove reverse_copy

copy_backward remove_copy rotate

fill remove_copy_if 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

Page 50: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

50

Fig. 22.12 | Nonmutating sequence algorithms.

Nonmodifying sequence algorithms

adjacent_find find find_if

count find_each mismatch

count_if find_end search

equal find_first_of search_n

Page 51: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

51

Fig. 22.13 | Numerical algorithms from header file <numeric>.

Numerical algorithms from header file <numeric>

accumulate partial_sum

inner_product adjacent_difference

Page 52: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 53: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 54: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 55: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 56: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 indices (subscripts)

– 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>

Page 57: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

57

Performance Tip 22.7

Choose the vector container for the best random-access performance.

Page 58: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 59: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 60: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

60 1 // Fig. 22.14: Fig22_14.cpp

2 // Demonstrating Standard Library vector class template.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <vector> // vector class-template definition

8 using std::vector;

9

10 // prototype for function template printVector

11 template < typename T > void printVector( const vector< T > &integers2 );

12

13 int main()

14 {

15 const int SIZE = 6; // define array size

16 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; // initialize array

17 vector< int > integers; // create vector of ints

18

19 cout << "The initial size of integers is: " << integers.size()

20 << "\nThe initial capacity of integers is: " << integers.capacity();

21

22 // function push_back is in every sequence collection

23 integers.push_back( 2 );

24 integers.push_back( 3 );

25 integers.push_back( 4 );

26

27 cout << "\nThe size of integers is: " << integers.size()

28 << "\nThe capacity of integers is: " << integers.capacity();

29 cout << "\n\nOutput array using pointer notation: ";

Outline

Fig22_14.cpp

(1 of 3)

Define a vector called integers that stores int values

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 to accommodate more elementsAdd elements to the end of the vector

Page 61: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

6130

31 // display array using pointer notation

32 for ( int *ptr = array; ptr != array + SIZE; ptr++ )

33 cout << *ptr << ' ';

34

35 cout << "\nOutput vector using iterator notation: ";

36 printVector( integers );

37 cout << "\nReversed contents of vector integers: ";

38

39 // two const reverse iterators

40 vector< int >::const_reverse_iterator reverseIterator;

41 vector< int >::const_reverse_iterator tempIterator = integers.rend();

42

43 // display vector in reverse order using reverse_iterator

44 for ( reverseIterator = integers.rbegin();

45 reverseIterator!= tempIterator; ++reverseIterator )

46 cout << *reverseIterator << ' ';

47

48 cout << endl;

49 return 0;

50 } // end main

Outline

Fig22_14.cpp

(2 of 3)

reverseIterator iterates from the position returned by rbegin until just before the position returned by rend to output the vector elements in reverse order

Page 62: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

6251

52 // function template for outputting vector elements

53 template < typename T > void printVector( const vector< T > &integers2 )

54 {

55 typename vector< T >::const_iterator constIterator; // const_iterator

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 initial size of integers is: 0 The initial capacity of integers is: 0 The size of integers is: 3 The 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

Outline

Fig22_14.cpp

(3 of 3)

constIterator iterates through the vector and outputs its contents

Tell the compiler that vector< T > ::const_iterator is expected to be a type in every specialization

The vector’s capacity increases to accommodate the growing size

Page 63: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 64: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 65: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

65

22.2.1 vector Sequence Container (Cont.)

• 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

Page 66: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

66

22.2.1 vector Sequence Container (Cont.)

• 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>

Page 67: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 68: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 69: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

69 1 // Fig. 22.15: Fig22_15.cpp

2 // Testing Standard Library vector class template

3 // element-manipulation functions.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #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()

14 {

15 const int SIZE = 6;

16 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };

17 std::vector< int > integers( array, array + SIZE );

18 std::ostream_iterator< int > output( cout, " " );

19

20 cout << "Vector integers contains: ";

21 std::copy( integers.begin(), integers.end(), output );

22

23 cout << "\nFirst element of integers: " << integers.front()

24 << "\nLast element of integers: " << integers.back();

25

26 integers[ 0 ] = 7; // set first element to 7

27 integers.at( 2 ) = 10; // set element at position 2 to 10

28

29 // insert 22 as 2nd element

30 integers.insert( integers.begin() + 1, 22 );

Outline

Fig22_15.cpp

(1 of 3)

Initialize integers with the contents of array from location array up to just before location array + SIZE

output can be used to output integers separated by single spaces via cout

Copy the entire contents of vector integers to the standard output

<algorithm> must be included to use STL algorithms

References to first and last elements of integers

Access individual elements of integers

Insert 22 as the second element

Page 70: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

7031

32 cout << "\n\nContents of vector integers after changes: ";

33 std::copy( integers.begin(), integers.end(), output );

34

35 // access out-of-range element

36 try

37 {

38 integers.at( 100 ) = 777;

39 } // end try

40 catch ( std::out_of_range outOfRange ) // out_of_range exception

41 {

42 cout << "\n\nException: " << outOfRange.what();

43 } // end catch

44

45 // erase first element

46 integers.erase( integers.begin() );

47 cout << "\n\nVector integers after erasing first element: ";

48 std::copy( integers.begin(), integers.end(), output );

49

50 // erase remaining elements

51 integers.erase( integers.begin(), integers.end() );

52 cout << "\nAfter erasing all elements, vector integers "

53 << ( integers.empty() ? "is" : "is not" ) << " empty";

54

55 // insert elements from array

56 integers.insert( integers.begin(), array, array + SIZE );

57 cout << "\n\nContents of vector integers before clear: ";

58 std::copy( integers.begin(), integers.end(), output );

Outline

Fig22_15.cpp

(2 of 3)

Member function at throws an out_of_range exception

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

Page 71: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

7159

60 // empty integers; clear calls erase to empty a collection

61 integers.clear();

62 cout << "\nAfter clear, vector integers "

63 << ( integers.empty() ? "is" : "is not" ) << " empty" << endl;

64 return 0;

65 } // end main Vector integers contains: 1 2 3 4 5 6 First element of integers: 1 Last element of integers: 6 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

Outline

Fig22_15.cpp

(3 of 3)

Empty the vector

Page 72: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 73: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 74: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

74

Fig. 22.16 | Some STL exception types.

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.

invalid_argument Indicates an invalid argument was passed to a function.

length_error Indicates an attempt to create too long a container, string, etc.

bad_alloc Indicates that an attempt to allocate memory with s (or with an allocator) failed because not enough memory was available.

Page 75: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 76: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 77: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 78: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 79: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

79 1 // Fig. 22.17: Fig22_17.cpp

2 // Standard library list class template test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <list> // list class-template definition

8 #include <algorithm> // copy algorithm

9 #include <iterator> // ostream_iterator

10

11 // prototype for function template printList

12 template < typename T > void printList( const std::list< T > &listRef );

13

14 int main()

15 {

16 const int SIZE = 4;

17 int array[ SIZE ] = { 2, 6, 4, 8 };

18 std::list< int > values; // create list of ints

19 std::list< int > otherValues; // create list of ints

20

21 // insert items in values

22 values.push_front( 1 );

23 values.push_front( 2 );

24 values.push_back( 4 );

25 values.push_back( 3 );

26

27 cout << "values contains: ";

28 printList( values );

Outline

Fig22_17.cpp

(1 of 5)

Instantiate two list objects capable of storing integers

Insert integers at the beginning and end of values

Page 80: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

8029

30 values.sort(); // sort values

31 cout << "\nvalues after sorting contains: ";

32 printList( values );

33

34 // insert elements of array into otherValues

35 otherValues.insert( otherValues.begin(), array, array + SIZE );

36 cout << "\nAfter insert, otherValues contains: ";

37 printList( otherValues );

38

39 // remove otherValues elements and insert at end of values

40 values.splice( values.end(), otherValues );

41 cout << "\nAfter splice, values contains: ";

42 printList( values );

43

44 values.sort(); // sort values

45 cout << "\nAfter sort, values contains: ";

46 printList( values );

47

48 // insert elements of array into otherValues

49 otherValues.insert( otherValues.begin(), array, array + SIZE );

50 otherValues.sort();

51 cout << "\nAfter insert, otherValues contains: ";

52 printList( otherValues );

Outline

Fig22_17.cpp

(2 of 5)

Arrange the elements in the list in ascending order

Remove the elements in otherValues and insert them at the end of values

Page 81: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

8153

54 // remove otherValues elements and insert into values in sorted order

55 values.merge( otherValues );

56 cout << "\nAfter merge:\n values contains: ";

57 printList( values );

58 cout << "\n otherValues contains: ";

59 printList( otherValues );

60

61 values.pop_front(); // remove element from front

62 values.pop_back(); // remove element from back

63 cout << "\nAfter pop_front and pop_back:\n values contains: "

64 printList( values );

65

66 values.unique(); // remove duplicate elements

67 cout << "\nAfter unique, values contains: ";

68 printList( values );

69

70 // swap elements of values and otherValues

71 values.swap( otherValues );

72 cout << "\nAfter swap:\n values contains: ";

73 printList( values );

74 cout << "\n otherValues contains: ";

75 printList( otherValues );

76

77 // replace contents of values with elements of otherValues

78 values.assign( otherValues.begin(), otherValues.end() );

79 cout << "\nAfter assign, values contains: ";

80 printList( values );

Outline

Fig22_17.cpp

(3 of 5)

Remove all elements of otherValues and insert them in sorted order in values

Remove duplicate elements in values

Exchange the contents of values with the contents of otherValues

Replace the contents of values with the elements in otherValues

Page 82: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

8281

82 // remove otherValues elements and insert into values in sorted order

83 values.merge( otherValues );

84 cout << "\nAfter merge, values contains: ";

85 printList( values );

86

87 values.remove( 4 ); // remove all 4s

88 cout << "\nAfter remove( 4 ), values contains: ";

89 printList( values );

90 cout << endl;

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 if ( listRef.empty() ) // list is empty

99 cout << "List is empty";

100 else

101 {

102 std::ostream_iterator< T > output( cout, " " );

103 std::copy( listRef.begin(), listRef.end(), output );

104 } // end else

105 } // end function printList

Outline

Fig22_17.cpp

(4 of 5)

Delete all copies of the value 4 from values

Page 83: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

83Outline

Fig22_17.cpp

(5 of 5)

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

Page 84: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 85: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

85

Performance Tip 22.13

In general, deque has slightly higher overhead than vector.

Page 86: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 87: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

87 1 // Fig. 22.18: Fig22_18.cpp

2 // Standard Library class deque test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <deque> // deque class-template definition

8 #include <algorithm> // copy algorithm

9 #include <iterator> // ostream_iterator

10

11 int main()

12 {

13 std::deque< double > values; // create deque of doubles

14 std::ostream_iterator< double > output( cout, " " );

15

16 // insert elements in values

17 values.push_front( 2.2 );

18 values.push_front( 3.5 );

19 values.push_back( 1.1 );

20

21 cout << "values contains: ";

22

23 // use subscript operator to obtain elements of values

24 for ( unsigned int i = 0; i < values.size(); i++ )

25 cout << values[ i ] << ' ';

26

27 values.pop_front(); // remove first element

28 cout << "\nAfter pop_front, values contains: ";

29 std::copy( values.begin(), values.end(), output );

Outline

Fig22_18.cpp

(1 of 2)

Instantiate a deque that can store double values

Insert elements at the beginning and end of the deque

Retrieve the value in each element of the deque for output

Remove the first element of the deque

Page 88: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

8830

31 // use subscript operator to modify element at location 1

32 values[ 1 ] = 5.4;

33 cout << "\nAfter values[ 1 ] = 5.4, values contains: ";

34 std::copy( values.begin(), values.end(), output );

35 cout << endl;

36 return 0;

37 } // end main 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

Outline

Fig22_18.cpp

(2 of 2)

Use the subscript operator to create an lvalue

Page 89: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 90: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

90

22.3.1 multiset Associative Container

•multiset associative container– Fast storage and retrieval of keys

– 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>

Page 91: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 92: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

92

22.3.1 multiset Associative Container (Cont.)

•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

Page 93: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

93

22.3.1 multiset Associative Container (Cont.)

•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

Page 94: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

94

22.3.1 multiset Associative Container (Cont.)

•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

Page 95: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

95 1 // Fig. 22.19: Fig22_19.cpp

2 // Testing Standard Library class multiset

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

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

15 int main()

16 {

17 const int SIZE = 10;

18 int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 };

19 Ims intMultiset; // Ims is typedef for "integer multiset"

20 std::ostream_iterator< int > output( cout, " " );

21

22 cout << "There are currently " << intMultiset.count( 15 )

23 << " values of 15 in the multiset\n";

24

25 intMultiset.insert( 15 ); // insert 15 in intMultiset

26 intMultiset.insert( 15 ); // insert 15 in intMultiset

27 cout << "After inserts, there are " << intMultiset.count( 15 )

28 << " values of 15 in the multiset\n\n";

Outline

Fig22_19.cpp

(1 of 3)

Create a new type name for a multiset of integers in ascending order

Count the number of occurrences of the value 15 in intMultiset

Add the value 15 to intMultiset twice

Page 96: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

9629

30 // iterator that cannot be used to change element values

31 Ims::const_iterator result;

32

33 // find 15 in intMultiset; find returns iterator

34 result = intMultiset.find( 15 );

35

36 if ( result != intMultiset.end() ) // if iterator not at end

37 cout << "Found value 15\n"; // found search value 15

38

39 // find 20 in intMultiset; find returns iterator

40 result = intMultiset.find( 20 );

41

42 if ( result == intMultiset.end() ) // will be true hence

43 cout << "Did not find value 20\n"; // did not find 20

44

45 // insert elements of array a into intMultiset

46 intMultiset.insert( a, a + SIZE );

47 cout << "\nAfter insert, intMultiset contains:\n";

48 std::copy( intMultiset.begin(), intMultiset.end(), output );

49

50 // determine lower and upper bound of 22 in intMultiset

51 cout << "\n\nLower bound of 22: "

52 << *( intMultiset.lower_bound( 22 ) );

53 cout << "\nUpper bound of 22: " << *( intMultiset.upper_bound( 22 ) );

54

55 // p represents pair of const_iterators

56 std::pair< Ims::const_iterator, Ims::const_iterator > p;

Outline

Fig22_19.cpp

(2 of 3)

Locate the value 15 in intMultiset

Insert the elements of array a into intMultiset

Locate the earliest occurrence of the value 22 in intMultiset

Locate the position after the last occurrence of the value 22 in intMultiset

Page 97: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

9757

58 // use equal_range to determine lower and upper bound

59 // of 22 in intMultiset

60 p = intMultiset.equal_range( 22 );

61

62 cout << "\n\nequal_range of 22:" << "\n Lower bound: "

63 << *( p.first ) << "\n Upper bound: " << *( p.second );

64 cout << endl;

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 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

Outline

Fig22_19.cpp

(3 of 3)

Obtain the results of both a lower_bound and an upper_bound operation from a single function call

A pair contains two public data members, first and second

Page 98: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

98

22.3.2 set Associative Container

•set associative container– Fast storage and retrieval of unique 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

Page 99: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

99 1 // Fig. 22.20: Fig22_20.cpp

2 // Standard Library class set test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <set>

8

9 // define short name for set type used in this program

10 typedef std::set< double, std::less< double > > DoubleSet;

11

12 #include <algorithm>

13 #include <iterator> // ostream_iterator

14

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 // p represents pair containing const_iterator and bool

26 std::pair< DoubleSet::const_iterator, bool > p;

Outline

Fig22_20.cpp

(1 of 2)

Create a new type name for a set of double values ordered in ascending order

Second 2.1 value (a duplicate) will be ignored

Define a pair object to store the result of set member function insert

Page 100: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

10027

28 // insert 13.8 in doubleSet; insert returns pair in which

29 // p.first represents location of 13.8 in doubleSet and

30 // p.second represents whether 13.8 was inserted

31 p = doubleSet.insert( 13.8 ); // value not in set

32 cout << "\n\n" << *( p.first )

33 << ( p.second ? " was" : " was not" ) << " inserted";

34 cout << "\ndoubleSet contains: ";

35 std::copy( doubleSet.begin(), doubleSet.end(), output );

36

37 // insert 9.5 in doubleSet

38 p = doubleSet.insert( 9.5 ); // value already in set

39 cout << "\n\n" << *( p.first )

40 << ( p.second ? " was" : " was not" ) << " inserted";

41 cout << "\ndoubleSet contains: ";

42 std::copy( doubleSet.begin(), doubleSet.end(), output );

43 cout << endl;

44 return 0;

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

Outline

Fig22_20.cpp

(2 of 2)

Iterator p.first points to the value 13.8 in the set

bool value p.second is true if the value was inserted

Page 101: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 102: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 103: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

103 1 // Fig. 22.21: Fig22_21.cpp

2 // Standard Library class multimap test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <map> // map class-template definition

8

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 cout << "There are currently " << pairs.count( 15 )

17 << " pairs with key 15 in the multimap\n";

18

19 // insert two value_type objects in pairs

20 pairs.insert( Mmid::value_type( 15, 2.7 ) );

21 pairs.insert( Mmid::value_type( 15, 99.3 ) );

22

23 cout << "After inserts, there are " << pairs.count( 15 )

24 << " pairs with key 15\n\n";

Outline

Fig22_21.cpp

(1 of 2)

Define an alias for a multimap type with int keys and double values, in ascending order

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

Page 104: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

10425

26 // insert five value_type objects in pairs

27 pairs.insert( Mmid::value_type( 30, 111.11 ) );

28 pairs.insert( Mmid::value_type( 10, 22.22 ) );

29 pairs.insert( Mmid::value_type( 25, 33.333 ) );

30 pairs.insert( Mmid::value_type( 20, 9.345 ) );

31 pairs.insert( Mmid::value_type( 5, 77.54 ) );

32

33 cout << "Multimap pairs contains:\nKey\tValue\n";

34

35 // use const_iterator to walk through elements of pairs

36 for ( Mmid::const_iterator iter = pairs.begin();

37 iter != pairs.end(); ++iter )

38 cout << iter->first << '\t' << iter->second << '\n';

39

40 cout << endl;

41 return 0;

42 } // end main 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

Outline

Fig22_21.cpp

(2 of 2)

Use const_iterator iter to access the keys and values in pairs

Page 105: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

105

22.3.4 map Associative Container

•map associative container– Fast storage and retrieval of keys and associated values

(key/value pairs)• Stored as pair objects

• Duplicate keys 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 creates an association

– Insertions and deletions can be made anywhere

– Requires header file <map>

Page 106: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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)

Page 107: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

107 1 // Fig. 22.22: Fig22_22.cpp

2 // Standard Library class map test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <map> // map class-template definition

8

9 // define short name for map type used in this program

10 typedef std::map< int, double, std::less< int > > Mid;

11

12 int main()

13 {

14 Mid pairs;

15

16 // insert eight value_type objects in pairs

17 pairs.insert( Mid::value_type( 15, 2.7 ) );

18 pairs.insert( Mid::value_type( 30, 111.11 ) );

19 pairs.insert( Mid::value_type( 5, 1010.1 ) );

20 pairs.insert( Mid::value_type( 10, 22.22 ) );

21 pairs.insert( Mid::value_type( 25, 33.333 ) );

22 pairs.insert( Mid::value_type( 5, 77.54 ) ); // dup ignored

23 pairs.insert( Mid::value_type( 20, 9.345 ) );

24 pairs.insert( Mid::value_type( 15, 99.3 ) ); // dup ignored

25

26 cout << "pairs contains:\nKey\tValue\n";

Outline

Fig22_22.cpp

(1 of 3)

Page 108: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

10827

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

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

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';

42

43 cout << endl;

44 return 0;

45 } // end main

Outline

Fig22_22.cpp

(2 of 3)

Replace the value for the key 25 with the new value 9999.99

Insert a new key/value pair in the map

Page 109: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

109Outline

Fig22_22.cpp

(3 of 3)

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

Page 110: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

– You 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

Page 111: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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• Vector is the 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>

Page 112: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 113: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

113

Performance Tip 22.17

For the best performance, use class vector as the underlying container for a stack.

Page 114: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

114 1 // Fig. 22.23: Fig22_23.cpp

2 // Standard Library adapter stack test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <stack> // stack adapter definition

8 #include <vector> // vector class-template definition

9 #include <list> // list class-template definition

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 // stack with underlying vector

23 std::stack< int, std::vector< int > > intVectorStack;

24

25 // stack with underlying list

26 std::stack< int, std::list< int > > intListStack;

Outline

Fig22_23.cpp

(1 of 3)

Specify integer stacks using each of the three sequence containers as the underlying data structure

Page 115: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

11527

28 // push the values 0-9 onto each stack

29 cout << "Pushing onto intDequeStack: ";

30 pushElements( intDequeStack );

31 cout << "\nPushing onto intVectorStack: ";

32 pushElements( intVectorStack );

33 cout << "\nPushing onto intListStack: ";

34 pushElements( intListStack );

35 cout << endl << endl;

36

37 // display and remove elements from each stack

38 cout << "Popping from intDequeStack: ";

39 popElements( intDequeStack );

40 cout << "\nPopping from intVectorStack: ";

41 popElements( intVectorStack );

42 cout << "\nPopping from intListStack: ";

43 popElements( intListStack );

44 cout << endl;

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 {

53 stackRef.push( i ); // push element onto stack

54 cout << stackRef.top() << ' '; // view (and display ) top element

55 } // end for

56 } // end function pushElements

Outline

Fig22_23.cpp

(2 of 3)

Place an integer on top of the stack

Retrieve, but not remove, the top element

Page 116: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

11657

58 // pop elements from stack object to which stackRef refers

59 template< typename T > void popElements( T &stackRef )

60 {

61 while ( !stackRef.empty() )

62 {

63 cout << stackRef.top() << ' '; // view (and display) top element

64 stackRef.pop(); // remove top element

65 } // end while

66 } // end function popElements 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

Outline

Fig22_23.cpp

(3 of 3)

Retrieve and display the top element

Remove, and discard, the top element

Page 117: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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• deque is the 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>

Page 118: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 119: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

119

Performance Tip 22.19

For the best performance, use class deque as the underlying container for a queue.

Page 120: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

120 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;

6

7 #include <queue> // queue adapter definition

8

9 int main()

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 );

17

18 cout << "Popping from values: ";

Outline

Fig22_24.cpp

(1 of 2)Instantiate a queue that stores double values

Add elements to the queue

Page 121: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

12119

20 // pop elements from queue

21 while ( !values.empty() )

22 {

23 cout << values.front() << ' '; // view front element

24 values.pop(); // remove element

25 } // end while

26

27 cout << endl;

28 return 0;

29 } // end main Popping from values: 3.2 9.8 5.4

Outline

Fig22_24.cpp

(2 of 2)

Read the first element in the queue for output

Remove the first element in the queue

Page 122: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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• vector is the default

Page 123: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 124: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 125: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

125

Performance Tip 22.21

For the best performance, use class vector as the underlying container for a priority_queue.

Page 126: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

126 1 // Fig. 22.25: Fig22_25.cpp

2 // Standard Library adapter priority_queue test program.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <queue> // priority_queue adapter definition

8

9 int main()

10 {

11 std::priority_queue< double > priorities; // create priority_queue

12

13 // push elements onto priorities

14 priorities.push( 3.2 );

15 priorities.push( 9.8 );

16 priorities.push( 5.4 );

17

18 cout << "Popping from priorities: ";

19

20 // pop element from priority_queue

21 while ( !priorities.empty() )

22 {

23 cout << priorities.top() << ' '; // view top element

24 priorities.pop(); // remove top element

25 } // end while

26

27 cout << endl;

28 return 0;

29 } // end main Popping from priorities: 9.8 5.4 3.2

Outline

Fig22_25.cpp

(1 of 1)

Instantiate a priority_queue that stores double values using a vector as the underlying data structure

Add elements to the priority_queue

Retrieve the highest-priority element in the priority_queue for output

Remove the highest-priority element in the priority_queue

Page 127: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

127

22.5 Algorithms

• STL algorithms– STL separates algorithms from the containers

• Elements of containers are accessed through iterators

• Much easier to add new algorithms

Page 128: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 129: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 C-style, pointer-based arrays, on STL containers and on user-defined data structures.

Page 130: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 131: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

131

22.5.1 fill, fill_n, generate and generate_n

• 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

Page 132: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

132

22.5.1 fill, fill_n, generate and generate_n (Cont.)

• 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

Page 133: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

133

22.5.1 fill, fill_n, generate and generate_n (Cont.)

• 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

Page 134: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

134 1 // Fig. 22.26: Fig22_26.cpp

2 // Standard Library algorithms fill, fill_n, generate and generate_n.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <algorithm> // algorithm definitions

8 #include <vector> // vector class-template definition

9 #include <iterator> // ostream_iterator

10

11 char nextLetter(); // prototype of generator function

12

13 int main()

14 {

15 std::vector< char > chars( 10 );

16 std::ostream_iterator< char > output( cout, " " );

17 std::fill( chars.begin(), chars.end(), '5' ); // fill chars with 5s

18

19 cout << "Vector chars after filling with 5s:\n";

20 std::copy( chars.begin(), chars.end(), output );

21

22 // fill first five elements of chars with As

23 std::fill_n( chars.begin(), 5, 'A' );

24

25 cout << "\n\nVector chars after filling five elements with As:\n";

26 std::copy( chars.begin(), chars.end(), output );

27

28 // generate values for all elements of chars with nextLetter

29 std::generate( chars.begin(), chars.end(), nextLetter );

Outline

Fig22_26.cpp

(1 of 2)

Define a 10-element vector that stores char values

Place the character '5' in every element of chars

Place the character 'A' in the first five elements of chars

Place the result of a call to generator function nextLetter in every element of chars

Page 135: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

13530

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 std::generate_n( chars.begin(), 5, nextLetter );

36

37 cout << "\n\nVector chars after generating K-O for the"

38 << " first five elements:\n";

39 std::copy( chars.begin(), chars.end(), output );

40 cout << endl;

41 return 0;

42 } // end main

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

Outline

Fig22_26.cpp

(2 of 2)Place the result of a call to generator function nextLetter in the first five elements of chars

Page 136: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

136

22.5.2 equal, mismatch and lexicographical_compare

• 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

Page 137: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

137

22.5.2 equal, mismatch and lexicographical_compare (Cont.)

• 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

Page 138: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

138

22.5.2 equal, mismatch and lexicographical_compare (Cont.)

• 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

Page 139: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

139 1 // Fig. 22.27: Fig22_27.cpp

2 // Standard Library functions equal, mismatch and lexicographical_compare.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <algorithm> // algorithm definitions

8 #include <vector> // vector class-template definition

9 #include <iterator> // ostream_iterator

10

11 int main()

12 {

13 const int SIZE = 10;

14 int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

15 int a2[ SIZE ] = { 1, 2, 3, 4, 1000, 6, 7, 8, 9, 10 };

16 std::vector< int > v1( a1, a1 + SIZE ); // copy of a1

17 std::vector< int > v2( a1, a1 + SIZE ); // copy of a1

18 std::vector< int > v3( a2, a2 + SIZE ); // copy of a2

19 std::ostream_iterator< int > output( cout, " " );

20

21 cout << "Vector v1 contains: ";

22 std::copy( v1.begin(), v1.end(), output );

23 cout << "\nVector v2 contains: ";

24 std::copy( v2.begin(), v2.end(), output );

25 cout << "\nVector v3 contains: ";

26 std::copy( v3.begin(), v3.end(), output );

Outline

Fig22_27.cpp

(1 of 3)

Page 140: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14027

28 // compare vectors v1 and v2 for equality

29 bool result = std::equal( v1.begin(), v1.end(), v2.begin() );

30 cout << "\n\nVector v1 " << ( result ? "is" : "is not" )

31 << " equal to vector v2.\n";

32

33 // compare vectors v1 and v3 for equality

34 result = std::equal( v1.begin(), v1.end(), v3.begin() );

35 cout << "Vector v1 " << ( result ? "is" : "is not" )

36 << " equal to vector v3.\n";

37

38 // location represents pair of vector iterators

39 std::pair< std::vector< int >::iterator,

40 std::vector< int >::iterator > location;

41

42 // check for mismatch between v1 and v3

43 location = std::mismatch( v1.begin(), v1.end(), v3.begin() );

44 cout << "\nThere is a mismatch between v1 and v3 at location "

45 << ( location.first - v1.begin() ) << "\nwhere v1 contains "

46 << *location.first << " and v3 contains " << *location.second

47 << "\n\n";

48

49 char c1[ SIZE ] = "HELLO";

50 char c2[ SIZE ] = "BYE BYE";

Outline

Fig22_27.cpp

(2 of 3)

Compare v1 and v2 for equality

Compare v1 and v3 for equality

Locate the mismatched elements in v1 and v3

Determine the actual location of the mismatch relative to the beginning of the vectors

Page 141: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14151

52 // perform lexicographical comparison of c1 and c2

53 result = std::lexicographical_compare( c1, c1 + SIZE, c2, c2 + SIZE );

54 cout << c1 << ( result ? " is less than " :

55 " is greater than or equal to " ) << c2 << endl;

56 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 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

Outline

Fig22_27.cpp

(3 of 3)

Compare the contents of c1 and c2

Pointers into arrays can be used as random-access iterators

Page 142: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

142

22.5.3 remove, remove_if, remove_copy and remove_copy_if

• 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

Page 143: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14322.5.3 remove, remove_if, remove_copy and remove_copy_if (Cont.)

• 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

Page 144: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14422.5.3 remove, remove_if, remove_copy and remove_copy_if (Cont.)

• 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

Page 145: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14522.5.3 remove, remove_if, remove_copy and remove_copy_if (Cont.)

• 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

Page 146: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

146 1 // Fig. 22.28: Fig22_28.cpp

2 // Standard Library functions remove, remove_if,

3 // remove_copy and remove_copy_if.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #include <algorithm> // algorithm definitions

9 #include <vector> // vector class-template definition

10 #include <iterator> // ostream_iterator

11

12 bool greater9( int ); // prototype

13

14 int main()

15 {

16 const int SIZE = 10;

17 int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };

18 std::ostream_iterator< int > output( cout, " " );

19 std::vector< int > v( a, a + SIZE ); // copy of a

20 std::vector< int >::iterator newLastElement;

21

22 cout << "Vector v before removing all 10s:\n ";

23 std::copy( v.begin(), v.end(), output );

24

25 // remove all 10s from v

26 newLastElement = std::remove( v.begin(), v.end(), 10 );

27 cout << "\nVector v after removing all 10s:\n ";

28 std::copy( v.begin(), newLastElement, output );

Outline

Fig22_28.cpp

(1 of 4)

Eliminate all elements with the value 10 in v

Page 147: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14729

30 std::vector< int > v2( a, a + SIZE ); // copy of a

31 std::vector< int > c( SIZE, 0 ); // instantiate vector c

32 cout << "\n\nVector v2 before removing all 10s and copying:\n ";

33 std::copy( v2.begin(), v2.end(), output );

34

35 // copy from v2 to c, removing 10s in the process

36 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 );

39

40 std::vector< int > v3( a, a + SIZE ); // copy of a

41 cout << "\n\nVector v3 before removing all elements"

42 << "\ngreater than 9:\n ";

43 std::copy( v3.begin(), v3.end(), output );

44

45 // remove elements greater than 9 from v3

46 newLastElement = std::remove_if( v3.begin(), v3.end(), greater9 );

47 cout << "\nVector v3 after removing all elements"

48 << "\ngreater than 9:\n ";

49 std::copy( v3.begin(), newLastElement, output );

50

51 std::vector< int > v4( a, a + SIZE ); // copy of a

52 std::vector< int > c2( SIZE, 0 ); // instantiate vector c2

53 cout << "\n\nVector v4 before removing all elements"

54 << "\ngreater than 9 and copying:\n ";

55 std::copy( v4.begin(), v4.end(), output );

Outline

Fig22_28.cpp

(2 of 4)Copy all elements that do not have

the value 10 from v2 to c

This vector constructor receives the number of elements in the vector and the initial value for those elements

Delete all elements with values greater than 9 from v3

Page 148: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

14856

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;

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

Outline

Fig22_28.cpp

(3 of 4)Copy all elements that have values not greater than 9 from v4 to c2

Page 149: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

149 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 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

Outline

Fig22_28.cpp

(4 of 4)

Page 150: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

150

22.5.4 replace, replace_if, replace_copy and replace_copy_if

• 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

Page 151: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

15122.5.4 replace, replace_if, replace_copy and replace_copy_if (Cont.)

• 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

Page 152: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

15222.5.4 replace, replace_if, replace_copy and replace_copy_if (Cont.)

• 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

Page 153: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

15322.5.4 replace, replace_if, replace_copy and replace_copy_if (Cont.)

• 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

Page 154: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

154 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 using std::cout;

6 using std::endl;

7

8 #include <algorithm>

9 #include <vector>

10 #include <iterator> // ostream_iterator

11

12 bool greater9( int ); // predicate function prototype

13

14 int main()

15 {

16 const int SIZE = 10;

17 int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };

18 std::ostream_iterator< int > output( cout, " " );

19

20 std::vector< int > v1( a, a + SIZE ); // copy of a

21 cout << "Vector v1 before replacing all 10s:\n ";

22 std::copy( v1.begin(), v1.end(), output );

23

24 // replace all 10s in v1 with 100

25 std::replace( v1.begin(), v1.end(), 10, 100 );

26 cout << "\nVector v1 after replacing 10s with 100s:\n ";

27 std::copy( v1.begin(), v1.end(), output );

Outline

Fig22_29.cpp

(1 of 4)

Replace all elements with the value 10 in v1 with the new value 100

Page 155: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

15528

29 std::vector< int > v2( a, a + SIZE ); // copy of a

30 std::vector< int > c1( SIZE ); // instantiate vector c1

31 cout << "\n\nVector v2 before replacing all 10s and copying:\n ";

32 std::copy( v2.begin(), v2.end(), output );

33

34 // copy from v2 to c1, replacing 10s with 100s

35 std::replace_copy( v2.begin(), v2.end(), c1.begin(), 10, 100 );

36 cout << "\nVector c1 after replacing all 10s in v2:\n ";

37 std::copy( c1.begin(), c1.end(), output );

38

39 std::vector< int > v3( a, a + SIZE ); // copy of a

40 cout << "\n\nVector v3 before replacing values greater than 9:\n ";

41 std::copy( v3.begin(), v3.end(), output );

42

43 // replace values greater than 9 in v3 with 100

44 std::replace_if( v3.begin(), v3.end(), greater9, 100 );

45 cout << "\nVector v3 after replacing all values greater"

46 << "\nthan 9 with 100s:\n ";

47 std::copy( v3.begin(), v3.end(), output );

48

49 std::vector< int > v4( a, a + SIZE ); // copy of a

50 std::vector< int > c2( SIZE ); // instantiate vector c2‘

51 cout << "\n\nVector v4 before replacing all values greater "

52 << "than 9 and copying:\n ";

53 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 value 10 with the new value 100

Replace all elements in v3 that are greater than 9

Page 156: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

15654

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;

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

Outline

Fig22_29.cpp

(3 of 4)

Copy all elements in v4 into c2, replacing elements with values greater than 9 with the value 100

Page 157: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

157Outline

Fig22_29.cpp

(4 of 4)

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 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

Page 158: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 159: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 160: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 161: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 162: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 163: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 164: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

164 1 // Fig. 22.30: Fig22_30.cpp

2 // Mathematical algorithms of the Standard Library.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <algorithm> // algorithm definitions

8 #include <numeric> // accumulate is defined here

9 #include <vector>

10 #include <iterator>

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 int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

20 std::vector< int > v( a1, a1 + SIZE ); // copy of a1

21 std::ostream_iterator< int > output( cout, " " );

22

23 cout << "Vector v before random_shuffle: ";

24 std::copy( v.begin(), v.end(), output );

25

26 std::random_shuffle( v.begin(), v.end() ); // shuffle elements of v

27 cout << "\nVector v after random_shuffle: ";

28 std::copy( v.begin(), v.end(), output );

Outline

Fig22_30.cpp

(1 of 4)

Randomly reorder the elements in v

Page 165: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

16529

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 cout << "\n\nVector v2 contains: ";

33 std::copy( v2.begin(), v2.end(), output );

34

35 // count number of elements in v2 with value 8

36 int result = std::count( v2.begin(), v2.end(), 8 );

37 cout << "\nNumber of elements matching 8: " << result;

38

39 // count number of elements in v2 that are greater than 9

40 result = std::count_if( v2.begin(), v2.end(), greater9 );

41 cout << "\nNumber of elements greater than 9: " << result;

42

43 // locate minimum element in v2

44 cout << "\n\nMinimum element in Vector v2 is: "

45 << *( std::min_element( v2.begin(), v2.end() ) );

46

47 // locate maximum element in v2

48 cout << "\nMaximum element in Vector v2 is: "

49 << *( std::max_element( v2.begin(), v2.end() ) );

50

51 // calculate sum of elements in v

52 cout << "\n\nThe total of the elements in Vector v is: "

53 << std::accumulate( v.begin(), v.end(), 0 );

54

55 // output square of every element in v

56 cout << "\n\nThe square of every integer in Vector v is:\n";

57 std::for_each( v.begin(), v.end(), outputSquare );

Outline

Fig22_30.cpp

(2 of 4)

Count the elements with the value 8 in v2

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

Output the square of every element in v

Page 166: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

16658

59 std::vector< int > cubes( SIZE ); // instantiate vector cubes

60

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;

66 return 0;

67 } // end main

68

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

Outline

Fig22_30.cpp

(3 of 4)Take the cube of every element in v and store them in cubes

Page 167: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

167Outline

Fig22_30.cpp

(4 of 4)

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 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

Page 168: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 169: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

169

22.5.6 Basic Searching and Sorting Algorithms

• 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

Page 170: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

170

22.5.6 Basic Searching and Sorting Algorithms (Cont.)

• 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

Page 171: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

171

22.5.6 Basic Searching and Sorting Algorithms (Cont.)

• 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

Page 172: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

172

22.5.6 Basic Searching and Sorting Algorithms (Cont.)

• 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

Page 173: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

173 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 #include <algorithm> // algorithm definitions

8 #include <vector> // vector class-template definition

9 #include <iterator>

10

11 bool greater10( int value ); // predicate function prototype

12

13 int main()

14 {

15 const int SIZE = 10;

16 int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 };

17 std::vector< int > v( a, a + SIZE ); // copy of a

18 std::ostream_iterator< int > output( cout, " " );

19

20 cout << "Vector v contains: ";

21 std::copy( v.begin(), v.end(), output ); // display output vector

22

23 // locate first occurrence of 16 in v

24 std::vector< int >::iterator location;

25 location = std::find( v.begin(), v.end(), 16 );

26

27 if ( location != v.end() ) // found 16

28 cout << "\n\nFound 16 at location " << ( location - v.begin() );

29 else // 16 not found

30 cout << "\n\n16 not found";

Outline

Fig22_31.cpp

(1 of 3)

Locate the value 16 in v

Page 174: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

17431

32 // locate first occurrence of 100 in v

33 location = std::find( v.begin(), v.end(), 100 );

34

35 if ( location != v.end() ) // found 100

36 cout << "\nFound 100 at location " << ( location - v.begin() );

37 else // 100 not found

38 cout << "\n100 not found";

39

40 // locate first occurrence of value greater than 10 in v

41 location = std::find_if( v.begin(), v.end(), greater10 );

42

43 if ( location != v.end() ) // found value greater than 10

44 cout << "\n\nThe first value greater than 10 is " << *location

45 << "\nfound at location " << ( location - v.begin() );

46 else // value greater than 10 not found

47 cout << "\n\nNo values greater than 10 were found";

48

49 // sort elements of v

50 std::sort( v.begin(), v.end() );

51 cout << "\n\nVector v after sort: ";

52 std::copy( v.begin(), v.end(), output );

53

54 // use binary_search to locate 13 in v

55 if ( std::binary_search( v.begin(), v.end(), 13 ) )

56 cout << "\n\n13 was found in v";

57 else

58 cout << "\n\n13 was not found in v";

Outline

Fig22_31.cpp

(2 of 3)

Locate the first value in v that is greater than 10

Arrange the elements in v in ascending order

Determine whether the value 13 is in v by performing a binary search

Page 175: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

17559

60 // use binary_search to locate 100 in v

61 if ( std::binary_search( v.begin(), v.end(), 100 ) )

62 cout << "\n100 was found in v";

63 else

64 cout << "\n100 was not found in v";

65

66 cout << endl;

67 return 0;

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

Outline

Fig22_31.cpp

(3 of 3)

Page 176: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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.

Page 177: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

177

22.5.7 swap, iter_swap and swap_ranges

• STL algorithm function swap– Swap two values

• Takes as arguments two references to values being swapped

• STL algorithm function iter_swap– Swap two values pointed to by iterators

• Takes as arguments two forward iterators pointing to elements whose values are being swapped

Page 178: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

178

22.5.7 swap, iter_swap and swap_ranges (Cont.)

• 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)

Page 179: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

179 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 using std::endl;

6

7 #include <algorithm> // algorithm definitions

8 #include <iterator>

9

10 int main()

11 {

12 const int SIZE = 10;

13 int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

14 std::ostream_iterator< int > output( cout, " " );

15

16 cout << "Array a contains:\n ";

17 std::copy( a, a + SIZE, output ); // display array a

18

19 // swap elements at locations 0 and 1 of array a

20 std::swap( a[ 0 ], a[ 1 ] );

21

22 cout << "\nArray a after swapping a[0] and a[1] using swap:\n ";

23 std::copy( a, a + SIZE, output ); // display array a

24

25 // use iterators to swap elements at locations 0 and 1 of array a

26 std::iter_swap( &a[ 0 ], &a[ 1 ] ); // swap with iterators

27 cout << "\nArray a after swapping a[0] and a[1] using iter_swap:\n ";

28 std::copy( a, a + SIZE, output );

Outline

Fig22_32.cpp

(1 of 2)

Exchange the first and second elements of array a

Treat pointers to the first and second elements of array a as iterators

Page 180: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

18029

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 );

33

34 cout << "\nArray a after swapping the first five elements\n"

35 << "with the last five elements:\n ";

36 std::copy( a, a + SIZE, output );

37 cout << endl;

38 return 0;

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

Outline

Fig22_32.cpp

(2 of 2)

Exchange the first five elements of a with the next five elements of a

Page 181: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

181

22.5.8 copy_backward, merge, unique and reverse

• 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

Page 182: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

182

22.5.8 copy_backward, merge, unique and reverse (Cont.)

• 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

Page 183: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

183

22.5.8 copy_backward, merge, unique and reverse (Cont.)

• 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

Page 184: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

184

22.5.8 copy_backward, merge, unique and reverse (Cont.)

• 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

Page 185: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

185 1 // Fig. 22.33: Fig22_33.cpp

2 // Standard Library functions copy_backward, merge, unique and reverse.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <algorithm> // algorithm definitions

8 #include <vector> // vector class-template definition

9 #include <iterator> // ostream_iterator

10

11 int main()

12 {

13 const int SIZE = 5;

14 int a1[ SIZE ] = { 1, 3, 5, 7, 9 };

15 int a2[ SIZE ] = { 2, 4, 5, 7, 9 };

16 std::vector< int > v1( a1, a1 + SIZE ); // copy of a1

17 std::vector< int > v2( a2, a2 + SIZE ); // copy of a2

18 std::ostream_iterator< int > output( cout, " " );

19

20 cout << "Vector v1 contains: ";

21 std::copy( v1.begin(), v1.end(), output ); // display vector output

22 cout << "\nVector v2 contains: ";

23 std::copy( v2.begin(), v2.end(), output ); // display vector output

24

25 std::vector< int > results( v1.size() );

26

27 // place elements of v1 into results in reverse order

28 std::copy_backward( v1.begin(), v1.end(), results.end() );

29 cout << "\n\nAfter copy_backward, results contains: ";

30 std::copy( results.begin(), results.end(), output );

Outline

Fig22_33.cpp

(1 of 3)

Copy elements in v1 into results by starting from the element before v1.end()and working toward the beginning

Page 186: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

18631

32 std::vector< int > results2( v1.size() + v2.size() );

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 );

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 );

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;

53 } // end main

Outline

Fig22_33.cpp

(2 of 3)

Combine sorted vectors v1 and v2 into sorted vector results2

Eliminate duplicate values from results2

Reverse all elements in v1

Page 187: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

187Outline

Fig22_33.cpp

(3 of 3)

Vector v1 contains: 1 3 5 7 9 Vector v2 contains: 2 4 5 7 9 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 After unique results2 contains: 1 2 3 4 5 7 9 Vector v1 after reverse: 9 7 5 3 1

Page 188: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

188

22.5.9 inplace_merge, unique_copy and reverse_copy

• 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

Page 189: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

189

22.5.9 inplace_merge, unique_copy and reverse_copy (Cont.)

• 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

Page 190: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

190

22.5.9 inplace_merge, unique_copy and reverse_copy (Cont.)

• 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

Page 191: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

191 1 // Fig. 22.34: Fig22_34.cpp

2 // Standard Library algorithms inplace_merge,

3 // reverse_copy and unique_copy.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #include <algorithm> // algorithm definitions

9 #include <vector> // vector class-template definition

10 #include <iterator> // back_inserter definition

11

12 int main()

13 {

14 const int SIZE = 10;

15 int a1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 };

16 std::vector< int > v1( a1, a1 + SIZE ); // copy of a

17 std::ostream_iterator< int > output( cout, " " );

18

19 cout << "Vector v1 contains: ";

20 std::copy( v1.begin(), v1.end(), output );

21

22 // merge first half of v1 with second half of v1 such that

23 // 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;

Outline

Fig22_34.cpp

(1 of 2)

Merge the first five elements in v1 with the remaining five elements in v1

Page 192: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

19230

31 // copy only unique elements of v1 into results1

32 std::unique_copy(

33 v1.begin(), v1.end(), std::back_inserter( results1 ) );

34 cout << "\nAfter unique_copy results1 contains: ";

35 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 std::reverse_copy(

41 v1.begin(), v1.end(), std::back_inserter( results2 ) );

42 cout << "\nAfter reverse_copy, results2 contains: ";

43 std::copy( results2.begin(), results2.end(), output );

44 cout << endl;

45 return 0;

46 } // end main 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

Outline

Fig22_34.cpp

(2 of 2)

Make a copy of all unique elements in v1 and place the copied elements in results1

Use back_inserter to insert new elements into results1 rather than replace existing elements

Put a reversed copy of the elements in v1 into results2

Page 193: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 194: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 195: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 196: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 197: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 198: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

198 1 // Fig. 22.35: Fig22_35.cpp

2 // Standard Library algorithms includes, set_difference,

3 // set_intersection, set_symmetric_difference and set_union.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #include <algorithm> // algorithm definitions

9 #include <iterator> // ostream_iterator

10

11 int main()

12 {

13 const int SIZE1 = 10, SIZE2 = 5, SIZE3 = 20;

14 int a1[ SIZE1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

15 int a2[ SIZE2 ] = { 4, 5, 6, 7, 8 };

16 int a3[ SIZE2 ] = { 4, 5, 6, 11, 15 };

17 std::ostream_iterator< int > output( cout, " " );

18

19 cout << "a1 contains: ";

20 std::copy( a1, a1 + SIZE1, output ); // display array a1

21 cout << "\na2 contains: ";

22 std::copy( a2, a2 + SIZE2, output ); // display array a2

23 cout << "\na3 contains: ";

24 std::copy( a3, a3 + SIZE2, output ); // display array a3

25

26 // determine whether set a2 is completely contained in a1

27 if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) )

28 cout << "\n\na1 includes a2";

29 else

30 cout << "\n\na1 does not include a2";

Outline

Fig22_35.cpp

(1 of 3)

Determine whether every element in a2 is contained in a1

Page 199: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

19931

32 // determine whether set a3 is completely contained in a1

33 if ( std::includes( a1, a1 + SIZE1, a3, a3 + SIZE2 ) )

34 cout << "\na1 includes a3";

35 else

36 cout << "\na1 does not include a3";

37

38 int difference[ SIZE1 ];

39

40 // determine elements of a1 not in a2

41 int *ptr = std::set_difference( a1, a1 + SIZE1,

42 a2, a2 + SIZE2, difference );

43 cout << "\n\nset_difference of a1 and a2 is: ";

44 std::copy( difference, ptr, output );

45

46 int intersection[ SIZE1 ];

47

48 // determine elements in both a1 and a2

49 ptr = std::set_intersection( a1, a1 + SIZE1,

50 a2, a2 + SIZE2, intersection );

51 cout << "\n\nset_intersection of a1 and a2 is: ";

52 std::copy( intersection, ptr, output );

53

54 int symmetric_difference[ SIZE1 + SIZE2 ];

Outline

Fig22_35.cpp

(2 of 3)

Copy the elements in a1 that are not in a2 into difference

Store the elements common to both a1 and a2 in intersection

Page 200: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

20055

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 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 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

Outline

Fig22_35.cpp

(3 of 3)

Copy the elements in a1 that are not in a3 and the elements in a3 that are not in a1 into symmetric_difference

Place the combined set of all elements in a1 or a3 into unionSet

Page 201: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

201

22.5.11 lower_bound, upper_bound and equal_range

• 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

Page 202: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

202

22.5.11 lower_bound, upper_bound and equal_range (Cont.)

• 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

Page 203: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

203

22.5.11 lower_bound, upper_bound and equal_range (Cont.)

• 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)

Page 204: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

204 1 // Fig. 22.36: Fig22_36.cpp

2 // Standard Library functions lower_bound, upper_bound and

3 // equal_range for a sorted sequence of values.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #include <algorithm> // algorithm definitions

9 #include <vector> // vector class-template definition

10 #include <iterator> // ostream_iterator

11

12 int main()

13 {

14 const int SIZE = 10;

15 int a1[ SIZE ] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 };

16 std::vector< int > v( a1, a1 + SIZE ); // copy of a1

17 std::ostream_iterator< int > output( cout, " " );

18

19 cout << "Vector v contains:\n";

20 std::copy( v.begin(), v.end(), output );

21

22 // determine lower-bound insertion point for 6 in v

23 std::vector< int >::iterator lower;

24 lower = std::lower_bound( v.begin(), v.end(), 6 );

25 cout << "\n\nLower bound of 6 is element "

26 << ( lower - v.begin() ) << " of vector v";

Outline

Fig22_36.cpp

(1 of 4)

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

Page 205: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

20527

28 // determine upper-bound insertion point for 6 in v

29 std::vector< int >::iterator upper;

30 upper = std::upper_bound( v.begin(), v.end(), 6 );

31 cout << "\nUpper bound of 6 is element "

32 << ( upper - v.begin() ) << " of vector v";

33

34 // use equal_range to determine both the lower- and

35 // upper-bound insertion points for 6

36 std::pair< std::vector< int >::iterator,

37 std::vector< int >::iterator > eq;

38 eq = std::equal_range( v.begin(), v.end(), 6 );

39 cout << "\nUsing equal_range:\n Lower bound of 6 is element "

40 << ( eq.first - v.begin() ) << " of vector v";

41 cout << "\n Upper bound of 6 is element "

42 << ( eq.second - v.begin() ) << " of vector v";

43 cout << "\n\nUse lower_bound to locate the first point\n"

44 << "at which 5 can be inserted in order";

45

46 // determine lower-bound insertion point for 5 in v

47 lower = std::lower_bound( v.begin(), v.end(), 5 );

48 cout << "\n Lower bound of 5 is element "

49 << ( lower - v.begin() ) << " of vector v";

50 cout << "\n\nUse upper_bound to locate the last point\n"

51 << "at which 7 can be inserted in order";

Outline

Fig22_36.cpp

(2 of 4)

Find the last location where 6 can be inserted in sorted order in vector v

Find the lower bound and upper bound for 6 in v using the equal_range algorithm

Page 206: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

20652

53 // determine upper-bound insertion point for 7 in v

54 upper = std::upper_bound( v.begin(), v.end(), 7 );

55 cout << "\n Upper bound of 7 is element "

56 << ( 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";

59

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 Lower bound of 5 is element "

64 << ( eq.first - v.begin() ) << " of vector v";

65 cout << "\n Upper bound of 5 is element "

66 << ( eq.second - v.begin() ) << " of vector v" << endl;

67 return 0;

68 } // end main

Outline

Fig22_36.cpp

(3 of 4)

Page 207: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

207Outline

Fig22_36.cpp

(4 of 4)

Vector v contains: 2 2 4 4 4 6 6 6 6 8 Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Using equal_range: Lower bound of 6 is element 5 of vector v Upper bound of 6 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 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

Page 208: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 child nodes are always less than or equal to parent node’s value

– Often called a maxheap

Page 209: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 210: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 211: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 212: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 213: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

213 1 // Fig. 22.37: Fig22_37.cpp

2 // Standard Library algorithms push_heap, pop_heap,

3 // make_heap and sort_heap.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7

8 #include <algorithm>

9 #include <vector>

10 #include <iterator>

11

12 int main()

13 {

14 const int SIZE = 10;

15 int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };

16 std::vector< int > v( a, a + SIZE ); // copy of a

17 std::vector< int > v2;

18 std::ostream_iterator< int > output( cout, " " );

19

20 cout << "Vector v before make_heap:\n";

21 std::copy( v.begin(), v.end(), output );

22

23 std::make_heap( v.begin(), v.end() ); // create heap from vector v

24 cout << "\nVector v after make_heap:\n";

25 std::copy( v.begin(), v.end(), output );

26

27 std::sort_heap( v.begin(), v.end() ); // sort elements with sort_heap

28 cout << "\nVector v after sort_heap:\n";

29 std::copy( v.begin(), v.end(), output );

Outline

Fig22_37.cpp

(1 of 4)

Arrange the elements of v into a heap

Sort the elements of v using heapsort

Page 214: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

21430

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;

35

36 // place elements of array a into v2 and

37 // maintain elements of v2 in heap

38 for ( int i = 0; i < SIZE; i++ )

39 {

40 v2.push_back( a[ i ] );

41 std::push_heap( v2.begin(), v2.end() );

42 cout << "\nv2 after push_heap(a[" << i << "]): ";

43 std::copy( v2.begin(), v2.end(), output );

44 } // end for

45

46 cout << endl;

47

48 // remove elements from heap in sorted order

49 for ( unsigned int j = 0; j < v2.size(); j++ )

50 {

51 cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";

52 std::pop_heap( v2.begin(), v2.end() - j );

53 std::copy( v2.begin(), v2.end(), output );

54 } // end for

55

56 cout << endl;

57 return 0;

58 } // end main

Outline

Fig22_37.cpp

(2 of 4)

Push value a[ i ] into the heap in v2

Insert value a[ i ] into v2

Remove the top heap element and place it in the jth-to-last position in v2

Page 215: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

215Outline

Fig22_37.cpp

(3 of 4)

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 Array a contains: 3 100 52 77 22 31 1 98 13 40 v2 after push_heap(a[0]): 3 v2 after push_heap(a[1]): 100 3 v2 after push_heap(a[2]): 100 3 52 v2 after push_heap(a[3]): 100 77 52 3 v2 after push_heap(a[4]): 100 77 52 3 22 v2 after push_heap(a[5]): 100 77 52 3 22 31 v2 after push_heap(a[6]): 100 77 52 3 22 31 1 v2 after push_heap(a[7]): 100 98 52 77 22 31 1 3 v2 after push_heap(a[8]): 100 98 52 77 22 31 1 3 13 v2 after push_heap(a[9]): 100 98 52 77 40 31 1 3 13 22 (continued at the top of next slide...)

Page 216: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

216Outline

Fig22_37.cpp

(4 of 4)

(...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

Page 217: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 218: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

218 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;

6

7 #include <algorithm>

8

9 int main()

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;

17 } // end main The minimum of 12 and 7 is: 7 The maximum of 12 and 7 is: 12 The minimum of 'G' and 'Z' is: G The maximum of 'G' and 'Z' is: Z

Outline

Fig22_38.cpp

(1 of 1)Determine which of 12 and 7 is smaller

Determine which of 12 and 7 is larger

Determine which of 'G' and 'Z' is less

Determine which of 'G' and 'Z' is greater

Page 219: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

219

Fig. 22.39 | Algorithms not covered in this chapter. (Part 1 of 5)

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.

Page 220: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

220

Fig. 22.39 | Algorithms not covered in this chapter. (Part 2 of 5)

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.

Page 221: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

221

Fig. 22.39 | Algorithms not covered in this chapter. (Part 3 of 5)

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_permutation Next lexicographical permutation of a sequence.

prev_permutation Previous lexicographical permutation of a sequence.

rotate 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.

rotate_copy 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.

adjacent_find 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.

Page 222: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

222

Fig. 22.39 | Algorithms not covered in this chapter. (Part 4 of 5)

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.

Page 223: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

223

Fig. 22.39 | Algorithms not covered in this chapter. (Part 5 of 5)

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.

Page 224: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

224

22.6 Class bitset

• Class bitset– Create and manipulate sets of bits

• 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

Page 225: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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 to off, off to on)

• Flips all bits if no argument is specified

– Subscript operator []• Returns a reference to a specified bit

Page 226: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 227: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 228: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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

Page 229: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

229 1 // Fig. 22.40: Fig22_40.cpp

2 // Using a bitset to demonstrate the Sieve of Eratosthenes.

3 #include <iostream>

4 using std::cin;

5 using std::cout;

6 using std::endl;

7

8 #include <iomanip>

9 using std::setw;

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

22 sieve.reset( 0 ); // reset first bit (number 0)

23 sieve.reset( 1 ); // reset second bit (number 1)

24

25 // perform Sieve of Eratosthenes

26 int finalBit = sqrt( static_cast< double > ( sieve.size() ) ) + 1;

Outline

Fig22_40.cpp

(1 of 4)

Create a bitset of 1024 bits, all set to “off” by default

Flip all bits to “on”

0 and 1 are not prime numbers

Determine when the algorithm should terminate

Page 230: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

23027

28 // determine all prime numbers from 2 to 1024

29 for ( int i = 2; i < finalBit; i++ )

30 {

31 if ( sieve.test( i ) ) // bit i is on

32 {

33 for ( int j = 2 * i; j < SIZE; j += i )

34 sieve.reset( j ); // set bit j off

35 } // end if

36 } // end for

37

38 cout << "The prime numbers in the range 2 to 1023 are:\n";

39

40 // display prime numbers in range 2-1023

41 for ( int k = 2, counter = 1; k < SIZE; k++ )

42 {

43 if ( sieve.test( k ) ) // bit k is on

44 {

45 cout << setw( 5 ) << k;

46

47 if ( counter++ % 12 == 0 ) // counter is a multiple of 12

48 cout << '\n';

49 } // end if

50 } // end for

51

52 cout << endl;

53

54 // get value from user to determine whether value is prime

55 cout << "\nEnter a value from 2 to 1023 (-1 to end): ";

56 cin >> value;

Outline

Fig22_40.cpp

(2 of 4)

If i is a prime number

All numbers that are multiples of i are not prime numbers

Check if k is a prime number

Page 231: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

23157

58 // determine whether user input is prime

59 while ( value != -1 )

60 {

61 if ( sieve[ value ] ) // prime number

62 cout << value << " is a prime number\n";

63 else // not a prime number

64 cout << value << " is not a prime number\n";

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

Outline

Fig22_40.cpp

(3 of 4)

Check if value is a prime number

Page 232: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

232Outline

Fig22_40.cpp

(4 of 4)

The prime numbers in the range 2 to 1023 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021

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

Page 233: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

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>

Page 234: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

234

Fig. 22.41 | Function objects in the Standard Library

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

Page 235: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

235Outline

Fig22_42.cpp

(1 of 3)

1 // Fig. 22.42: Fig22_42.cpp

2 // Demonstrating function objects.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 #include <vector> // vector class-template definition

8 #include <algorithm> // copy algorithm

9 #include <numeric> // accumulate algorithm

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;

18 } // end function sumSquares

Define function sumSquares

Page 236: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

236Outline

Fig22_42.cpp

(2 of 3)

19

20 // binary function class template defines overloaded operator()

21 // that adds the square of its second argument and running

22 // total in its first argument, then returns sum

23 template< typename T >

24 class SumSquaresClass : public std::binary_function< T, T, T >

25 {

26 public:

27 // add square of value to total and return result

28 T operator()( const T &total, const T &value )

29 {

30 return total + value * value;

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 int result;

41

42 cout << "vector integers contains:\n";

43 std::copy( integers.begin(), integers.end(), output );

44

45 // calculate sum of squares of elements of vector integers

46 // using binary function sumSquares

47 result = std::accumulate( integers.begin(), integers.end(),

48 0, sumSquares );

Define class SumSquaresClass which will be used to instantiate function objects

Pass a pointer to function sumSquares to accumulate

Page 237: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

237Outline

Fig22_42.cpp

(3 of 3)

49

50 cout << "\n\nSum of squares of elements in integers using "

51 << "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

58 cout << "\n\nSum of squares of elements in integers using "

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

Pass an instance of class SumSquaresClass (a function object) to accumulate

Page 238: 2008 Pearson Education, Inc. All rights reserved. 1 22 Standard Template Library (STL)

2008 Pearson Education, Inc. All rights reserved.

238

22.9 STL Web Resources

• C++ Resource Center– www.deitel.com/cplusplus/