0% found this document useful (0 votes)
36 views155 pages

2003 Prentice Hall, Inc. All Rights Reserved

The document outlines the Standard Template Library (STL) and its main components: containers, iterators, and algorithms. It describes the common sequence and associative container classes, their member functions, and common iterator types. Iterators are used to access container elements and behave similarly to pointers. Algorithms can be used with iterators to manipulate elements in a range.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views155 pages

2003 Prentice Hall, Inc. All Rights Reserved

The document outlines the Standard Template Library (STL) and its main components: containers, iterators, and algorithms. It describes the common sequence and associative container classes, their member functions, and common iterator types. Iterators are used to access container elements and behave similarly to pointers. Algorithms can be used with iterators to manipulate elements in a range.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 155

1

Chapter 21 - Standard Template Library


(STL)
Outline
21.1 Introduction to the Standard Template Library (STL)
21.1.1 Introduction to Containers
21.1.2 Introduction to Iterators
21.1.3 Introduction to Algorithms
21.2 Sequence Containers
21.2.1 vector Sequence Container
21.2.2 list Sequence Container
21.2.3 deque Sequence Container
21.3 Associative Containers
21.3.1 multiset Associative Container
21.3.2 set Associative Container
21.3.3 multimap Associative Container
21.3.4 map Associative Container
21.4 Container Adapters
21.4.1 stack Adapter
21.4.2 queue Adapter
21.4.3 priority_queue Adapter

 2003 Prentice Hall, Inc. All rights reserved.


2
Chapter 21 - Standard Template Library
(STL)
21.5 Algorithms
21.5.1 fill, fill_n, generate and generate_n
21.5.2 equal, mismatch and lexicographical_compare
21.5.3 remove, remove_if, remove_copy and remove_copy_if
21.5.4 replace, replace_if, replace_copy and replace_copy_if
21.5.5 Mathematical Algorithms
21.5.6 Basic Searching and Sorting Algorithms
21.5.7 swap, iter_swap and swap_ranges
21.5.8 copy_backward, merge, unique and reverse
21.5.9 inplace_merge, unique_copy and reverse_copy
21.5.10 Set Operations
21.5.11 lower_bound, upper_bound and equal_range
21.5.12 Heapsort
21.5.13 min and max
21.5.14 Algorithms Not Covered in This Chapter
21.6 Class bitset
21.7 Function Objects

 2003 Prentice Hall, Inc. All rights reserved.


3
21.1 Introduction to the Standard Template
Library (STL)
• STL
– Powerful, template-based components
• Containers: template data structures
• Iterators: like pointers, access elements of containers
• Algorithms: data manipulation, searching, sorting, etc.
– Object- oriented programming: reuse, reuse, reuse
– Only an introduction to STL, a huge class library

 2003 Prentice Hall, Inc. All rights reserved.


4

21.1.1 Introduction to Containers

• Three types of containers


– Sequence containers
• Linear data structures (vectors, linked lists)
• First-class container
– Associative containers
• Non-linear, can find elements quickly
• Key/value pairs
• First-class container
– Container adapters
• Near containers
– Similar to containers, with reduced functionality
• Containers have some common functions
 2003 Prentice Hall, Inc. All rights reserved.
5

STL Container Classes (Fig. 21.1)

• Sequence containers
– vector
– deque
– list
• Associative containers
– set
– multiset
– map
– multimap
• Container adapters
– stack
– queue
– priority_queue

 2003 Prentice Hall, Inc. All rights reserved.


6

Common STL Member Functions (Fig. 21.2)

• Member functions for all containers


– Default constructor, copy constructor, destructor
– empty
– max_size, size
– = < <= > >= == !=
– swap
• Functions for first-class containers
– begin, end
– rbegin, rend
– erase, clear

 2003 Prentice Hall, Inc. All rights reserved.


7

Common STL typedefs (Fig. 21.4)

• typedefs for first-class containers


– value_type
– reference
– const_reference
– pointer
– iterator
– const_iterator
– reverse_iterator
– const_reverse_iterator
– difference_type
– size_type

 2003 Prentice Hall, Inc. All rights reserved.


8

21.1.2 Introduction to Iterators

• Iterators similar to pointers


– Point to first element in a container
– Iterator operators same for all containers
• * dereferences
• ++ points to next element
• begin() returns iterator to first element
• end() returns iterator to last element
– Use iterators with sequences (ranges)
• Containers
• Input sequences: istream_iterator
• Output sequences: ostream_iterator

 2003 Prentice Hall, Inc. All rights reserved.


9

21.1.2 Introduction to Iterators

• Usage
– std::istream_iterator< int > inputInt( cin )
• Can read input from cin
• *inputInt
– Dereference to read first int from cin
• ++inputInt
– Go to next int in stream
– std::ostream_iterator< int > outputInt(cout)
• Can output ints to cout
• *outputInt = 7
– Outputs 7 to cout
• ++outputInt
– Advances iterator so we can output next int

 2003 Prentice Hall, Inc. All rights reserved.


10
1 // Fig. 21.5: fig21_05.cpp
2 // Demonstrating input and output with iterators.
Outline
3 #include <iostream>
4
fig21_05.cpp
5 using std::cout;
(1 of 2)
6 using std::cin;
7 using std::endl;
8
9
Note creation of
#include <iterator> // ostream_iterator and istream_iterator
10 istream_iterator. For
11 int main() compilation reasons, we use
12 { std:: rather than a using
13 statement.
cout << "Enter two integers: ";
14 Access and assign the iterator
15 // create istream_iterator for reading int values from cin like a pointer.
16 std::istream_iterator< int > inputInt( cin );
17
18 int number1 = *inputInt; // read int from standard input
19 ++inputInt; // move iterator to next input value
20 int number2 = *inputInt; // read int from standard input
21

 2003 Prentice Hall, Inc.


All rights reserved.
11
22 // create ostream_iterator for writing int values to cout
23 std::ostream_iterator< int > outputInt( cout );
Outline
24
25 cout << "The sum is: ";
fig21_05.cpp
26 *outputInt = number1 + number2; // output result to cout
(2 of 2)
27 cout << endl;
28
29 return 0; fig21_05.cpp
30 output (1 of 1)
31 } // end main

Enter two integers: 12 25


The sum is: 37
Create an
ostream_iterator is
similar. Assigning to this
iterator outputs to cout.

 2003 Prentice Hall, Inc.


All rights reserved.
12

Iterator Categories (Fig. 21.6)

• Input
– Read elements from container, can only move forward
• Output
– Write elements to container, only forward
• Forward
– Combines input and output, retains position
– Multi-pass (can pass through sequence twice)
• Bidirectional
– Like forward, but can move backwards as well
• Random access
– Like bidirectional, but can also jump to any element

 2003 Prentice Hall, Inc. All rights reserved.


13

Iterator Types Supported (Fig. 21.8)

• Sequence containers
– vector: random access
– deque: random access
– list: bidirectional
• Associative containers (all bidirectional)
– set
– multiset
– Map
– multimap
• Container adapters (no iterators supported)
– stack
– queue
– priority_queue

 2003 Prentice Hall, Inc. All rights reserved.


14

Iterator Operations (Fig. 21.10)

• All
– ++p, p++
• Input iterators
– *p
– p = p1
– p == p1, p != p1
• Output iterators
– *p
– p = p1
• Forward iterators
– Have functionality of input and output iterators

 2003 Prentice Hall, Inc. All rights reserved.


15

Iterator Operations (Fig. 21.10)

• Bidirectional
– --p, p--
• Random access
– p + i, p += i
– p - i, p -= i
– p[i]
– p < p1, p <= p1
– p > p1, p >= p1

 2003 Prentice Hall, Inc. All rights reserved.


16

21.1.3 Introduction to Algorithms

• STL has algorithms used generically across


containers
– Operate on elements indirectly via iterators
– Often operate on sequences of elements
• Defined by pairs of iterators
• First and last element
– Algorithms often return iterators
• find()
• Returns iterator to element, or end() if not found
– Premade algorithms save programmers time and effort

 2003 Prentice Hall, Inc. All rights reserved.


17

21.2 Sequence Containers

• Three sequence containers


– vector - based on arrays
– deque - based on arrays
– list - robust linked list

 2003 Prentice Hall, Inc. All rights reserved.


18

21.2.1 vector Sequence Container

• vector
– <vector>
– Data structure with contiguous memory locations
• Access elements with []
– Use when data must be sorted and easily accessible
• When memory exhausted
– Allocates larger, contiguous area of memory
– Copies itself there
– Deallocates old memory
• Has random access iterators

 2003 Prentice Hall, Inc. All rights reserved.


19

21.2.1 vector Sequence Container

• Declarations
– std::vector <type> v;
• type: int, float, etc.
• Iterators
– std::vector<type>::const_iterator iterVar;
• const_iterator cannot modify elements
– std::vector<type>::reverse_iterator iterVar;
• Visits elements in reverse order (end to beginning)
• Use rbegin to get starting point
• Use rend to get ending point

 2003 Prentice Hall, Inc. All rights reserved.


20

21.2.1 vector Sequence Container

• vector functions
– v.push_back(value)
• Add element to end (found in all sequence containers).
– v.size()
• Current size of vector
– v.capacity()
• How much vector can hold before reallocating memory
• Reallocation doubles size
– vector<type> v(a, a + SIZE)
• Creates vector v with elements from array a up to (not including)
a + SIZE

 2003 Prentice Hall, Inc. All rights reserved.


21

21.2.1 vector Sequence Container

• vector functions
– v.insert(iterator, value )
• Inserts value before location of iterator
– v.insert(iterator, array , array + SIZE)
• Inserts array elements (up to, but not including array + SIZE) into
vector
– v.erase( iterator )
• Remove element from container
– v.erase( iter1, iter2 )
• Remove elements starting from iter1 and up to (not including)
iter2
– v.clear()
• Erases entire container

 2003 Prentice Hall, Inc. All rights reserved.


22

21.2.1 vector Sequence Container

• vector functions operations


– v.front(), v.back()
• Return first and last element
– v.[elementNumber] = value;
• Assign value to an element
– v.at[elementNumber] = value;
• As above, with range checking
• out_of_bounds exception

 2003 Prentice Hall, Inc. All rights reserved.


23

21.2.1 vector Sequence Container

• ostream_iterator
– std::ostream_iterator< type >
Name( outputStream, separator );
• type: outputs values of a certain type
• outputStream: iterator output location
• separator: character separating outputs
• Example
– std::ostream_iterator< int > output( cout, " " );
– std::copy( iterator1, iterator2, output );
• Copies elements from iterator1 up to (not including)
iterator2 to output, an ostream_iterator

 2003 Prentice Hall, Inc. All rights reserved.


24
1 // Fig. 21.14: fig21_14.cpp
2 // Demonstrating standard library vector class template.
Outline
3 #include <iostream>
4
fig21_14.cpp
5 using std::cout;
(1 of 3)
6 using std::cin;
7 using std::endl;
8
9 #include <vector> // vector class-template definition
10
11 // prototype for function template printVector
12 template < class T >
13 void printVector( const std::vector< T > &integers2 );
14
15 int main()
16 {
Create a vector of ints.
17 const int SIZE = 6;
18 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
19
Call member functions.
20 std::vector< int > integers;
21
22 cout << "The initial size of integers is: "
23 << integers.size()
24 << "\nThe initial capacity of integers is: "
25 << integers.capacity();
26

 2003 Prentice Hall, Inc.


All rights reserved.
25
27 // function push_back is in every sequence collection
28 integers.push_back( 2 ); Add elements to end of Outline
29 integers.push_back( 3 ); vector using push_back.
30 integers.push_back( 4 );
fig21_14.cpp
31
(2 of 3)
32 cout << "\nThe size of integers is: " << integers.size()
33 << "\nThe capacity of integers is: "
34 << integers.capacity();
35
36 cout << "\n\nOutput array using pointer notation: ";
37
38 for ( int *ptr = array; ptr != array + SIZE; ++ptr )
39 cout << *ptr << ' ';
40
41 cout << "\nOutput vector using iterator notation: ";
42 printVector( integers );
43
44 cout << "\nReversed contents of vector integers: ";
45

 2003 Prentice Hall, Inc.


All rights reserved.
26
46 std::vector< int >::reverse_iterator reverseIterator;
47
Outline
48 for ( reverseIterator = integers.rbegin();
49 reverseIterator!= integers.rend();
Walk through vector
fig21_14.cpp
50 ++reverseIterator )
backwards using a(3 of 3)
51 cout << *reverseIterator << ' ';
52
reverse_iterator.
53 cout << endl;
54
55 return 0;
56
57 } // end main
Template function to walk
58
through vector forwards.
59 // function template for outputting vector elements
60 template < class T >
61 void printVector( const std::vector< T > &integers2 )
62 {
63 std::vector< T >::const_iterator constIterator;
64
65 for ( constIterator = integers2.begin();
66 constIterator != integers2.end();
67 constIterator++ )
68 cout << *constIterator << ' ';
69
70 } // end function printVector

 2003 Prentice Hall, Inc.


All rights reserved.
27
The initial size of v is: 0
The initial capacity of v is: 0
Outline
The size of v is: 3
The capacity of v is: 4
fig21_14.cpp
output (1 of 1)
Contents of array a using pointer notation: 1 2 3 4 5 6
Contents of vector v using iterator notation: 2 3 4
Reversed contents of vector v: 4 3 2

 2003 Prentice Hall, Inc.


All rights reserved.
28
1 // Fig. 21.15: fig21_15.cpp
2 // Testing Standard Library vector class template
Outline
3 // element-manipulation functions.
4 #include <iostream>
fig21_15.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <vector> // vector class-template definition
10 #include <algorithm> // copy algorithm
11
12 int main()
13 { Create vector (initialized
14 const int SIZE = 6; using an array) and
15 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; ostream_iterator.
16
17 std::vector< int > integers( array, array + SIZE );
18 std::ostream_iterator< int > output( cout, " " ); Copy range of iterators to output
19 (ostream_iterator).
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

 2003 Prentice Hall, Inc.


All rights reserved.
29
26 integers[ 0 ] = 7; // set first element to 7
27 integers.at( 2 ) = 10; // set element at position 2 to 10
Outline
28
29 // insert 22 as 2nd element
More vector member
fig21_15.cpp
30 integers.insert( integers.begin() + 1, 22 );
functions. (2 of 3)
31
32 cout << "\n\nContents of vector integers after changes: ";
33 std::copy( integers.begin(), integers.end(), output );
34
35 // access out-of-range element at has range checking, and
36 try { can throw an exception.
37 integers.at( 100 ) = 777;
38
39 } // end try
40
41 // catch out_of_range exception
42 catch ( std::out_of_range outOfRange ) {
43 cout << "\n\nException: " << outOfRange.what();
44
45 } // end catch
46
47 // erase first element
48 integers.erase( integers.begin() );
49 cout << "\n\nVector integers after erasing first element: ";
50 std::copy( integers.begin(), integers.end(), output );
51

 2003 Prentice Hall, Inc.


All rights reserved.
30
52 // erase remaining elements
53 integers.erase( integers.begin(), integers.end() );
Outline
54 cout << "\nAfter erasing all elements, vector integers "
55 << ( integers.empty() ? "is" : "is not" ) << " empty";
fig21_15.cpp
56
(3 of 3)
57 // insert elements from array
58 integers.insert( integers.begin(), array, array + SIZE );
59 cout << "\n\nContents of vector integers before clear: ";
60 std::copy( integers.begin(), integers.end(), output );
61
62 // empty integers; clear calls erase to empty a collection
63 integers.clear();
64 cout << "\nAfter clear, vector integers "
65 << ( integers.empty() ? "is" : "is not" ) << " empty";
66
67 cout << endl;
68
69 return 0;
70
71 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
31
Vector integers contains: 1 2 3 4 5 6
First element of integers: 1
Outline
Last element of integers: 6
 
fig21_15.cpp
Contents of vector integers after changes: 7 22 2 10 4 5 6
output (1 of 1)
 
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

 2003 Prentice Hall, Inc.


All rights reserved.
32

21.2.2 list Sequence Container

• list container
– Header <list>
– Efficient insertion/deletion anywhere in container
– Doubly-linked list (two pointers per node)
– Bidirectional iterators
– std::list< type > name;

 2003 Prentice Hall, Inc. All rights reserved.


33

21.2.2 list Sequence Container

• list functions for object t


– t.sort()
• Sorts in ascending order
– t.splice(iterator, otherObject );
• Inserts values from otherObject before iterator
– t.merge( otherObject )
• Removes otherObject and inserts it into t, sorted
– t.unique()
• Removes duplicate elements

 2003 Prentice Hall, Inc. All rights reserved.


34

21.2.2 list Sequence Container

• list functions
– t.swap(otherObject);
• Exchange contents
– t.assign(iterator1, iterator2)
• Replaces contents with elements in range of iterators
– t.remove(value)
• Erases all instances of value

 2003 Prentice Hall, Inc. All rights reserved.


35
1 // Fig. 21.17: fig21_17.cpp
2 // Standard library list class template test program.
Outline
3 #include <iostream>
4
fig21_17.cpp
5 using std::cout;
(1 of 5)
6 using std::endl;
7
8 #include <list> // list class-template definition
9 #include <algorithm> // copy algorithm
10
11 // prototype for function template printList
12 template < class T >
13 void printList( const std::list< T > &listRef );
14
15 int main()
16 {
17 const int SIZE = 4; Create two list objects.
18 int array[ SIZE ] = { 2, 6, 4, 8 };
19
20 std::list< int > values;
21 std::list< int > otherValues;
22
23 // insert items in values
24 values.push_front( 1 );
25 values.push_front( 2 );
26 values.push_back( 4 );
27 values.push_back( 3 );

 2003 Prentice Hall, Inc.


All rights reserved.
36
28
29 cout << "values contains: "; Various list member Outline
30 printList( values ); functions.
31
fig21_17.cpp
32 values.sort(); // sort values
(2 of 5)
33
34 cout << "\nvalues after sorting contains: ";
35 printList( values );
36
37 // insert elements of array into otherValues
38 otherValues.insert( otherValues.begin(),
39 array, array + SIZE );
40
41 cout << "\nAfter insert, otherValues contains: ";
42 printList( otherValues );
43
44 // remove otherValues elements and insert at end of values
45 values.splice( values.end(), otherValues );
46
47 cout << "\nAfter splice, values contains: ";
48 printList( values );
49
50 values.sort(); // sort values
51
52 cout << "\nAfter sort, values contains: ";
53 printList( values );
54

 2003 Prentice Hall, Inc.


All rights reserved.
37
55 // insert elements of array into otherValues
56 otherValues.insert( otherValues.begin(),
Outline
57 array, array + SIZE );
58 otherValues.sort();
fig21_17.cpp
59
(3 of 5)
60 cout << "\nAfter insert, otherValues contains: ";
61 printList( otherValues );
62
63 // remove otherValues elements and insert into values
64 // in sorted order
65 values.merge( otherValues );
66
67 cout << "\nAfter merge:\n values contains: ";
68 printList( values );
69 cout << "\n otherValues contains: ";
70 printList( otherValues );
71
72 values.pop_front(); // remove element from front
73 values.pop_back(); // remove element from back
74
75 cout << "\nAfter pop_front and pop_back:"
76 << "\n values contains: ";
77 printList( values );
78
79 values.unique(); // remove duplicate elements
80
81 cout << "\nAfter unique, values contains: ";
82 printList( values );
 2003 Prentice Hall, Inc.
All rights reserved.
38
83
84 // swap elements of values and otherValues
Outline
85 values.swap( otherValues );
86
fig21_17.cpp
87 cout << "\nAfter swap:\n values contains: ";
(4 of 5)
88 printList( values );
89 cout << "\n otherValues contains: ";
90 printList( otherValues );
91
92 // replace contents of values with elements of otherValues
93 values.assign( otherValues.begin(), otherValues.end() );
94
95 cout << "\nAfter assign, values contains: ";
96 printList( values );
97
98 // remove otherValues elements and insert into values
99 // in sorted order
100 values.merge( otherValues );
101
102 cout << "\nAfter merge, values contains: ";
103 printList( values );
104
105 values.remove( 4 ); // remove all 4s
106
107 cout << "\nAfter remove( 4 ), values contains: ";
108 printList( values );

 2003 Prentice Hall, Inc.


All rights reserved.
39
109
110 cout << endl;
Outline
111
112 return 0;
fig21_17.cpp
113
(5 of 5)
114 } // end main
115
116 // printList function template definition; uses
117 // ostream_iterator and copy algorithm to output list elements
118 template < class T >
119 void printList( const std::list< T > &listRef )
120 {
121 if ( listRef.empty() )
122 cout << "List is empty";
123
124 else {
125 std::ostream_iterator< T > output( cout, " " );
126 std::copy( listRef.begin(), listRef.end(), output );
127
128 } // end else
129
130 } // end function printList

 2003 Prentice Hall, Inc.


All rights reserved.
40
values contains: 2 1 4 3
values after sorting contains: 1 2 3 4
Outline
After insert, otherValues contains: 2 6 4 8
After splice, values contains: 1 2 3 4 2 6 4 8
fig21_17.cpp
After sort, values contains: 1 2 2 3 4 4 6 8
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
41

21.2.3 deque Sequence Container

• deque ("deek"): double-ended queue


– Header <deque>
– Indexed access using []
– Efficient insertion/deletion in front and back
– Non-contiguous memory: has "smarter" iterators
• Same basic operations as vector
– Also has
• push_front (insert at front of deque)
• pop_front (delete from front)

 2003 Prentice Hall, Inc. All rights reserved.


42
1 // Fig. 21.18: fig21_18.cpp
2 // Standard library class deque test program.
Outline
3 #include <iostream>
4
fig21_18.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <deque> // deque class-template definition
9 #include <algorithm> // copy algorithm
10
Create a deque, use member
11 int main() functions.
12 {
13 std::deque< double > values;
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 ( int i = 0; i < values.size(); ++i )
25 cout << values[ i ] << ' ';
26

 2003 Prentice Hall, Inc.


All rights reserved.
43
27 values.pop_front(); // remove first element
28
Outline
29 cout << "\nAfter pop_front, values contains: ";
30 std::copy( values.begin(), values.end(), output );
fig21_18.cpp
31
(2 of 2)
32 // use subscript operator to modify element at location 1
33 values[ 1 ] = 5.4;
34 fig21_18.cpp
35 cout << "\nAfter values[ 1 ] = 5.4, values contains: "; output (1 of 1)
36 std::copy( values.begin(), values.end(), output );
37
38 cout << endl;
39
40 return 0;
41
42 } // 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

 2003 Prentice Hall, Inc.


All rights reserved.
44

21.3 Associative Containers

• Associative containers
– Direct access to store/retrieve elements
– Uses keys (search keys)
– 4 types: multiset, set, multimap and map
• Keys in sorted order
• multiset and multimap allow duplicate keys
• multimap and map have keys and associated values
• multiset and set only have values

 2003 Prentice Hall, Inc. All rights reserved.


45

21.3.1 multiset Associative Container

• multiset
– Header <set>
– Fast storage, retrieval of keys (no values)
– Allows duplicates
– Bidirectional iterators
• Ordering of elements
– Done by comparator function object
• Used when creating multiset
– For integer multiset
• less<int> comparator function object
• multiset< int, std::less<int> > myObject;
• Elements will be sorted in ascending order

 2003 Prentice Hall, Inc. All rights reserved.


46

21.3.1 multiset Associative Container

• Multiset functions
– ms.insert(value)
• Inserts value into multiset
– ms.count(value)
• Returns number of occurrences of value
– ms.find(value)
• Returns iterator to first instance of value
– ms.lower_bound(value)
• Returns iterator to first location of value
– ms.upper_bound(value)
• Returns iterator to location after last occurrence of value

 2003 Prentice Hall, Inc. All rights reserved.


47

21.3.1 multiset Associative Container

• Class pair
– Manipulate pairs of values
– Pair objects contain first and second
• const_iterators
– For a pair object q
q = ms.equal_range(value)
• Sets first and second to lower_bound and
upper_bound for a given value

 2003 Prentice Hall, Inc. All rights reserved.


48
1 // Fig. 21.19: fig21_19.cpp
2 // Testing Standard Library class multiset
Outline
3 #include <iostream>
4
fig21_19.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
typedefs help clarify
8 #include <set> // multiset class-template definition
9
program. This declares an
integer multiset that stores
10 // define short name for multiset type used in this program
11 typedef std::multiset< int, std::less< int > > ims; values in ascending order.
12
13 #include <algorithm> // copy algorithm
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
20 ims intMultiset; // ims is typedef for "integer multiset"
21 std::ostream_iterator< int > output( cout, " " );
22
23 cout << "There are currently " << intMultiset.count( 15 )
24 << " values of 15 in the multiset\n";
25

 2003 Prentice Hall, Inc.


All rights reserved.
49
26 intMultiset.insert( 15 ); // insert 15 in intMultiset
27 intMultiset.insert( 15 ); // insert 15 in intMultiset
Outline
28
29 cout << "After inserts, there are "
fig21_19.cpp
30 << intMultiset.count( 15 )
(2 of 3)
31 << " values of 15 in the multiset\n\n";
32
33 // iterator that cannot be used to change element values
34 ims::const_iterator result;
Use member function find.
35
36 // find 15 in intMultiset; find returns iterator
37 result = intMultiset.find( 15 );
38
39 if ( result != intMultiset.end() ) // if iterator not at end
40 cout << "Found value 15\n"; // found search value 15
41
42 // find 20 in intMultiset; find returns iterator
43 result = intMultiset.find( 20 );
44
45 if ( result == intMultiset.end() ) // will be true hence
46 cout << "Did not find value 20\n"; // did not find 20
47
48 // insert elements of array a into intMultiset
49 intMultiset.insert( a, a + SIZE );
50
51 cout << "\nAfter insert, intMultiset contains:\n";
52 std::copy( intMultiset.begin(), intMultiset.end(), output );
53
 2003 Prentice Hall, Inc.
All rights reserved.
50
54 // determine lower and upper bound of 22 in intMultiset
55 cout << "\n\nLower bound of 22: "
Outline
56 << *( intMultiset.lower_bound( 22 ) );
57 cout << "\nUpper bound of 22: "
fig21_19.cpp
58 << *( intMultiset.upper_bound( 22 ) );
(3 of 3)
59
60 // p represents pair of const_iterators
61 std::pair< ims::const_iterator, ims::const_iterator > p;
62
Use a pair object to get the
63 // use equal_range to determine lower and upperlower
boundand upper bound for
64 // of 22 in intMultiset 22.
65 p = intMultiset.equal_range( 22 );
66
67 cout << "\n\nequal_range of 22:"
68 << "\n Lower bound: " << *( p.first )
69 << "\n Upper bound: " << *( p.second );
70
71 cout << endl;
72
73 return 0;
74
75 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
51
There are currently 0 values of 15 in the multiset
After inserts, there are 2 values of 15 in the multiset
Outline
 
Found value 15
fig21_19.cpp
Did not find value 20
output (1 of 1)
 
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

 2003 Prentice Hall, Inc.


All rights reserved.
52

21.3.2 set Associative Container

• set
– Header <set>
– Implementation identical to multiset
– Unique keys
• Duplicates ignored and not inserted
– Supports bidirectional iterators (but not random access)
– std::set< type, std::less<type> > name;

 2003 Prentice Hall, Inc. All rights reserved.


53
1 // Fig. 21.20: fig21_20.cpp
2 // Standard library class set test program.
Outline
3 #include <iostream>
4
fig21_20.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
Create set. Syntax similar to
8 #include <set>
9
multiset.
10 // define short name for set type used in this program
11 typedef std::set< double, std::less< double > > double_set;
12
13 #include <algorithm>
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
20 double_set doubleSet( a, a + SIZE );
21 std::ostream_iterator< double > output( cout, " " );
22
23 cout << "doubleSet contains: ";
24 std::copy( doubleSet.begin(), doubleSet.end(), output );
25

 2003 Prentice Hall, Inc.


All rights reserved.
54
26 // p represents pair containing const_iterator and bool
27 std::pair< double_set::const_iterator, bool > p;
Outline
28
29 // insert 13.8 in doubleSet; insert returns pair in which
fig21_20.cpp
30 // p.first represents location of 13.8 in doubleSet and
31 // p.second represents whether 13.8 was inserted pair object has a bool (2 of 3)
32 p = doubleSet.insert( 13.8 ); // value not in setvalue representing whether or
33 not the item was inserted.
34 cout << "\n\n" << *( p.first )
35 << ( p.second ? " was" : " was not" ) << " inserted";
36
37 cout << "\ndoubleSet contains: ";
38 std::copy( doubleSet.begin(), doubleSet.end(), output );
39
40 // insert 9.5 in doubleSet
41 p = doubleSet.insert( 9.5 ); // value already in set
42
43 cout << "\n\n" << *( p.first )
44 << ( p.second ? " was" : " was not" ) << " inserted";
45

 2003 Prentice Hall, Inc.


All rights reserved.
55
46 cout << "\ndoubleSet contains: ";
47 std::copy( doubleSet.begin(), doubleSet.end(), output );
Outline
48
49 cout << endl;
fig21_20.cpp
50
(3 of 3)
51 return 0;
52
53 } // end main fig21_20.cpp
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
56

21.3.3 multimap Associative Container

• multimap
– Header <map>
– Fast storage and retrieval of keys and associated values
• Has key/value pairs
– Duplicate keys allowed (multiple values for a single key)
• One-to-many relationship
• I.e., one student can take many courses
– Insert pair objects (with a key and value)
– Bidirectional iterators

 2003 Prentice Hall, Inc. All rights reserved.


57

21.3.3 multimap Associative Container

• Example
std::multimap< int, double, std::less< int > > mmapObject;
– Key type int
– Value type double
– Sorted in ascending order
• Use typedef to simplify code

typedef std::multimap<int, double, std::less<int>> mmid;


mmid mmapObject;
mmapObject.insert( mmid::value_type( 1, 3.4 ) );
– Inserts key 1 with value 3.4
– mmid::value_type creates a pair object

 2003 Prentice Hall, Inc. All rights reserved.


58
1 // Fig. 21.21: fig21_21.cpp
2 // Standard library class multimap test program.
Outline
3 #include <iostream>
4
fig21_21.cpp
5 using std::cout;
Definition for a multimap
(1 of 2)
6 using std::endl;
7
that maps integer keys to
8 #include <map> // map class-template definition double values.
9
10 // define short name for multimap type used in this program
11 typedef std::multimap< int, double, std::less< int > > mmid;
12
13 int main() Create multimap and insert
14 { key-value pairs.
15 mmid pairs;
16
17 cout << "There are currently " << pairs.count( 15 )
18 << " pairs with key 15 in the multimap\n";
19
20 // insert two value_type objects in pairs
21 pairs.insert( mmid::value_type( 15, 2.7 ) );
22 pairs.insert( mmid::value_type( 15, 99.3 ) );
23
24 cout << "After inserts, there are "
25 << pairs.count( 15 )
26 << " pairs with key 15\n\n";

 2003 Prentice Hall, Inc.


All rights reserved.
59
27
28 // insert five value_type objects in pairs
Outline
29 pairs.insert( mmid::value_type( 30, 111.11 ) );
30 pairs.insert( mmid::value_type( 10, 22.22 ) );
fig21_21.cpp
31 pairs.insert( mmid::value_type( 25, 33.333 ) );
(2 of 2)
32 pairs.insert( mmid::value_type( 20, 9.345 ) );
33 pairs.insert( mmid::value_type( 5, 77.54 ) );
34
35 Use iterator
to print entire
cout << "Multimap pairs contains:\nKey\tValue\n";
36 multimap.
37 // use const_iterator to walk through elements of pairs
38 for ( mmid::const_iterator iter = pairs.begin();
39 iter != pairs.end(); ++iter )
40 cout << iter->first << '\t'
41 << iter->second << '\n';
42
43 cout << endl;
44
45 return 0;
46
47 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
60
There are currently 0 pairs with key 15 in the multimap
After inserts, there are 2 pairs with key 15
Outline
 
Multimap pairs contains:
fig21_21.cpp
Key Value
output (1 of 1)
5 77.54
10 22.22
15 2.7
15 99.3
20 9.345
25 33.333
30 111.11

 2003 Prentice Hall, Inc.


All rights reserved.
61

21.3.4 map Associative Container

• map
– Header <map>
– Like multimap, but only unique key/value pairs
• One-to-one mapping (duplicates ignored)
– Use [] to access values
– Example: for map object m
m[30] = 4000.21;
• Sets the value of key 30 to 4000.21
– If subscript not in map, creates new key/value pair
• Type declaration
– std::map< int, double, std::less< int > >;

 2003 Prentice Hall, Inc. All rights reserved.


62
1 // Fig. 21.22: fig21_22.cpp
2 // Standard library class map test program.
Outline
3 #include <iostream>
4
fig21_22.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
Again, use typedefs to
8 #include <map> // map class-template definition
9
simplify declaration.
10 // define short name for map type used in this program
11 typedef std::map< int, double, std::less< int > > mid;
12
13 int main()
14 {
15 mid pairs;
16
Duplicate keys ignored.
17 // insert eight value_type objects in pairs
18 pairs.insert( mid::value_type( 15, 2.7 ) );
19 pairs.insert( mid::value_type( 30, 111.11 ) );
20 pairs.insert( mid::value_type( 5, 1010.1 ) );
21 pairs.insert( mid::value_type( 10, 22.22 ) );
22 pairs.insert( mid::value_type( 25, 33.333 ) );
23 pairs.insert( mid::value_type( 5, 77.54 ) ); // dupe ignored
24 pairs.insert( mid::value_type( 20, 9.345 ) );
25 pairs.insert( mid::value_type( 15, 99.3 ) ); // dupe ignored
26

 2003 Prentice Hall, Inc.


All rights reserved.
63
27 cout << "pairs contains:\nKey\tValue\n";
28
Outline
29 // use const_iterator to walk through elements of pairs
30 for ( mid::const_iterator iter = pairs.begin();
fig21_22.cpp
31 iter != pairs.end(); ++iter )
(2 of 2)
32 cout << iter->first << '\t'
33 << iter->second << '\n'; Can use subscript operator to
34 add or change key-value pairs.
35 // use subscript operator to change value for key 25
36 pairs[ 25 ] = 9999.99;
37
38 // use subscript operator insert value for key 40
39 pairs[ 40 ] = 8765.43;
40
41 cout << "\nAfter subscript operations, pairs contains:"
42 << "\nKey\tValue\n";
43
44 for ( mid::const_iterator iter2 = pairs.begin();
45 iter2 != pairs.end(); ++iter2 )
46 cout << iter2->first << '\t'
47 << iter2->second << '\n';
48
49 cout << endl;
50
51 return 0;
52
53 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
64
pairs contains:
Key Value
Outline
5 1010.1
10 22.22
fig21_22.cpp
15 2.7
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
65

21.4 Container Adapters

• Container adapters
– stack, queue and priority_queue
– Not first class containers
• Do not support iterators
• Do not provide actual data structure
– Programmer can select implementation
– Member functions push and pop

 2003 Prentice Hall, Inc. All rights reserved.


66

21.4.1 stack Adapter

• stack
– Header <stack>
– Insertions and deletions at one end
– Last-in, first-out (LIFO) data structure
– Can use vector, list, or deque (default)
– Declarations
stack<type, vector<type> > myStack;
stack<type, list<type> > myOtherStack;
stack<type> anotherStack; // default deque
• vector, list
– Implementation of stack (default deque)
– Does not change behavior, just performance (deque and
vector fastest)

 2003 Prentice Hall, Inc. All rights reserved.


67
1 // Fig. 21.23: fig21_23.cpp
2 // Standard library adapter stack test program.
Outline
3 #include <iostream>
4
fig21_23.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
8 #include <stack> // stack adapter definition
9 #include <vector> // vector class-template definition
10 #include <list> // list class-template definition
11
12 // popElements function-template prototype
13 template< class T >
14 void popElements( T &stackRef );
15
16 int main() Create stacks with various
17 { implementations.
18 // stack with default underlying deque
19 std::stack< int > intDequeStack;
20
21 // stack with underlying vector
22 std::stack< int, std::vector< int > > intVectorStack;
23
24 // stack with underlying list
25 std::stack< int, std::list< int > > intListStack;
26

 2003 Prentice Hall, Inc.


All rights reserved.
68
27 // push the values 0-9 onto each stack
28 for ( int i = 0; i < 10; ++i ) {
Outline
29 intDequeStack.push( i );
30 intVectorStack.push( i );
Use member function push. fig21_23.cpp
31 intListStack.push( i );
(2 of 3)
32
33 } // end for
34
35 // display and remove elements from each stack
36 cout << "Popping from intDequeStack: ";
37 popElements( intDequeStack );
38 cout << "\nPopping from intVectorStack: ";
39 popElements( intVectorStack );
40 cout << "\nPopping from intListStack: ";
41 popElements( intListStack );
42
43 cout << endl;
44
45 return 0;
46
47 } // end main
48

 2003 Prentice Hall, Inc.


All rights reserved.
69
49 // pop elements from stack object to which stackRef refers
50 template< class T >
Outline
51 void popElements( T &stackRef )
52 {
fig21_23.cpp
53 while ( !stackRef.empty() ) {
(3 of 3)
54 cout << stackRef.top() << ' '; // view top element
55 stackRef.pop(); // remove top element
56 fig21_23.cpp
57 } // end while output (1 of 1)
58
59 } // end function popElements

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

 2003 Prentice Hall, Inc.


All rights reserved.
70

21.4.2 queue Adapter

• queue
– Header <queue>
– Insertions at back, deletions at front
– First-in-first-out (FIFO) data structure
– Implemented with list or deque (default)
• std::queue<double> values;
• Functions
– push( element )
• Same as push_back, add to end
– pop( element )
• Implemented with pop_front, remove from front
– empty()
– size()

 2003 Prentice Hall, Inc. All rights reserved.


71
1 // Fig. 21.24: fig21_24.cpp
2 // Standard library adapter queue test program.
Outline
3 #include <iostream>
4
fig21_24.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <queue> // queue adapter definition
9
Create queue, add values
10 int main() using push.
11 {
12 std::queue< double > values;
13
14 // push elements onto queue values
15 values.push( 3.2 );
16 values.push( 9.8 );
17 values.push( 5.4 );
18
19 cout << "Popping from values: ";
20
21 while ( !values.empty() ) {
22 cout << values.front() << ' '; // view front element
23 values.pop(); // remove element
24
25 } // end while
26

 2003 Prentice Hall, Inc.


All rights reserved.
72
27 cout << endl;
28
Outline
29 return 0;
30
fig21_24.cpp
31 } // end main
(2 of 2)
Popping from values: 3.2 9.8 5.4
fig21_24.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
73

21.4.3 priority_queue Adapter

• priority_queue
– Header <queue>
– Insertions happen in sorted order, deletions from front
– Implemented with vector (default) or deque
– Highest priority element always removed first
• Heapsort algorithm puts largest elements at front
• less<T> default, programmer can specify other comparator
– Functions
• push(value), pop(value)
• top()
– View top element
• size()
• empty()

 2003 Prentice Hall, Inc. All rights reserved.


74
1 // Fig. 21.25: fig21_25.cpp
2 // Standard library adapter priority_queue test program.
Outline
3 #include <iostream>
4
fig21_25.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <queue> // priority_queue adapter definition
9
Create priority queue.
10 int main()
11 {
12 std::priority_queue< double > priorities;
13
14 // push elements onto priorities Insert items using push. When
15 priorities.push( 3.2 ); using pop, highest priority
16 priorities.push( 9.8 ); (largest) items removed first.
17 priorities.push( 5.4 );
18
19 cout << "Popping from priorities: ";
20
21 while ( !priorities.empty() ) {
22 cout << priorities.top() << ' '; // view top element
23 priorities.pop(); // remove top element
24
25 } // end while
26

 2003 Prentice Hall, Inc.


All rights reserved.
75
27 cout << endl;
28
Outline
29 return 0;
30
fig21_25.cpp
31 } // end main
(2 of 2)
Popping from priorities: 9.8 5.4 3.2
fig21_25.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
76

21.5 Algorithms

• Before STL
– Class libraries incompatible among vendors
– Algorithms built into container classes
• STL separates containers and algorithms
– Easier to add new algorithms
– More efficient, avoids virtual function calls
– <algorithm>

 2003 Prentice Hall, Inc. All rights reserved.


77

21.5.1 fill, fill_n, generate and generate_n

• Functions to change containers


– fill(iterator1, iterator2, value);
• Sets range of elements to value
– fill_n(iterator1, n, value);
• Sets n elements to value, starting at iterator1
– generate(iterator1, iterator2, function);
• Like fill, but calls function to set each value
– generate(iterator1, quantity, function)
• Like fill_n, ""

 2003 Prentice Hall, Inc. All rights reserved.


78
1 // Fig. 21.26: fig21_26.cpp
2 // Standard library algorithms fill, fill_n, generate
Outline
3 // and generate_n.
4 #include <iostream>
fig21_26.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
11
12 char nextLetter(); // prototype
Create vector of chars, to
13
be used with various
14 int main()
15 {
functions.
16 std::vector< char > chars( 10 );
Function fill.
17 std::ostream_iterator< char > output( cout, " " );
18
19 // fill chars with 5s
20 std::fill( chars.begin(), chars.end(), '5' );
21
22 cout << "Vector chars after filling with 5s:\n";
23 std::copy( chars.begin(), chars.end(), output );
24

 2003 Prentice Hall, Inc.


All rights reserved.
79
25 // fill first five elements of chars with As
26 std::fill_n( chars.begin(), 5, 'A' );
Outline
27
28 cout << "\n\nVector chars after filling five elements"
fig21_26.cpp
29 << " with As:\n";
Functions
(2generate
of 3) and
30 std::copy( chars.begin(), chars.end(), output );
31
generate_n use function
32 // generate values for all elements of chars with nextLetter nextLetter.
33 std::generate( chars.begin(), chars.end(), nextLetter );
34
35 cout << "\n\nVector chars after generating letters A-J:\n";
36 std::copy( chars.begin(), chars.end(), output );
37
38 // generate values for first five elements of chars
39 // with nextLetter
40 std::generate_n( chars.begin(), 5, nextLetter );
41
42 cout << "\n\nVector chars after generating K-O for the"
43 << " first five elements:\n";
44 std::copy( chars.begin(), chars.end(), output );
45
46 cout << endl;
47
48 return 0;
49
50 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
80
51
52 // returns next letter in the alphabet (starts with A)
Outline
53 char nextLetter()
54 {
fig21_26.cpp
55 static char letter = 'A';
(3 of 3)
56 return letter++;
57
58 } // end function nextLetter fig21_26.cpp
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
81
21.5.2 equal, mismatch and
lexicographical_compare
• Functions to compare sequences of values
– equal
• Returns true if sequences are equal (uses ==)
• Can return false if of unequal length
equal(iterator1, iterator2, iterator3);
• Compares sequence from iterator1 to iterator2 with
sequence beginning at iterator3
– mismatch
• Arguments same as equal
• Returns a pair object with iterators pointing to mismatch
– If no mismatch, pair iterators equal to last item
pair < iterator, iterator > myPairObject;
myPairObject = mismatch( iter1, iter2, iter3);

 2003 Prentice Hall, Inc. All rights reserved.


82
21.5.2 equal, mismatch and
lexicographical_compare
• Functions to compare sequences of values
– lexicographical_compare
• Compare contents of two character arrays
• Returns true if element in first sequence smaller than
corresponding element in second

bool result = lexicographical_compare(iter1, iter2,


iter3);

 2003 Prentice Hall, Inc. All rights reserved.


83
1 // Fig. 21.27: fig21_27.cpp
2 // Standard library functions equal,
Outline
3 // mismatch and lexicographical_compare.
4 #include <iostream>
fig21_27.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
11
12 int main()
13 {
14 const int SIZE = 10;
15 int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
16 int a2[ SIZE ] = { 1, 2, 3, 4, 1000, 6, 7, 8, 9, 10 };
17
18 std::vector< int > v1( a1, a1 + SIZE );
19 std::vector< int > v2( a1, a1 + SIZE );
20 std::vector< int > v3( a2, a2 + SIZE );
21
22 std::ostream_iterator< int > output( cout, " " );
23

 2003 Prentice Hall, Inc.


All rights reserved.
84
24 cout << "Vector v1 contains: ";
25 std::copy( v1.begin(), v1.end(), output );
Outline
26 cout << "\nVector v2 contains: ";
27 std::copy( v2.begin(), v2.end(), output );
fig21_27.cpp
28 cout << "\nVector v3 contains: ";
(2 of 3)
29 std::copy( v3.begin(), v3.end(), output );
Use function equal.
30
31 // compare vectors v1 and v2 for equality
Compares all of v1 with v2.
32 bool result =
33 std::equal( v1.begin(), v1.end(), v2.begin() );
34
35 cout << "\n\nVector v1 " << ( result ? "is" : "is not" )
36 << " equal to vector v2.\n";
37
38 // compare vectors v1 and v3 for equality
39 result = std::equal( v1.begin(), v1.end(), v3.begin() );
40 cout << "Vector v1 " << ( result ? "is" : "is not" )
41 << " equal to vector v3.\n";
42
43 // location represents pair of vector iterators
44 std::pair< std::vector< int >::iterator,
45 std::vector< int >::iterator > location;
Note use of function
46
mismatch.
47 // check for mismatch between v1 and v3
48 location =
49 std::mismatch( v1.begin(), v1.end(), v3.begin() );
50

 2003 Prentice Hall, Inc.


All rights reserved.
85
51 cout << "\nThere is a mismatch between v1 and v3 at "
52 << "location " << ( location.first - v1.begin() )
Outline
53 << "\nwhere v1 contains " << *location.first
54 << " and v3 contains " << *location.second
fig21_27.cpp
55 << "\n\n";
(3 of 3)
56
57 char c1[ SIZE ] = "HELLO";
Use lexicographical_compare.
58 char c2[ SIZE ] = "BYE BYE";
59
60 // perform lexicographical comparison of c1 and c2
61 result = std::lexicographical_compare(
62 c1, c1 + SIZE, c2, c2 + SIZE );
63
64 cout << c1
65 << ( result ? " is less than " :
66 " is greater than or equal to " )
67 << c2 << endl;
68
69 return 0;
70
71 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
86
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
Outline
Vector v3 contains: 1 2 3 4 1000 6 7 8 9 10
 
fig21_27.cpp
Vector v1 is equal to vector v2.
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
87
21.5.3 remove, remove_if, remove_copy and
remove_copy_if
• remove
– remove( iter1, iter2, value);
– Removes all instances of value in range (iter1-iter2)
• Moves instances of value towards end
• Does not change size of container or delete elements
– Returns iterator to "new" end of container
– Elements after new iterator are undefined (0)
• remove_copy
– Copies one vector to another while removing an element
– remove_copy(iter1, iter2, iter3, value);
• Copies elements not equal to value into iter3 (output
iterator)
• Uses range iter1-iter2
 2003 Prentice Hall, Inc. All rights reserved.
88
21.5.3 remove, remove_if, remove_copy and
remove_copy_if
• remove_if
– Like remove
• Returns iterator to last element
• Removes elements that return true for specified function
remove_if(iter1,iter2, function);
• Elements passed to function, which returns a bool
• remove_copy_if
– Like remove_copy and remove_if
– Copies range of elements to iter3, except those for which
function returns true
remove_copy_if(iter1, iter2, iter3, function);

 2003 Prentice Hall, Inc. All rights reserved.


89
1 // Fig. 21.28: fig21_28.cpp
2 // Standard library functions remove, remove_if,
Outline
3 // remove_copy and remove_copy_if.
4 #include <iostream>
fig21_28.cpp
5
(1 of 4)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
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
19 std::ostream_iterator< int > output( cout, " " );
20
21 std::vector< int > v( a, a + SIZE );
22 std::vector< int >::iterator newLastElement;
23
24 cout << "Vector v before removing all 10s:\n ";
25 std::copy( v.begin(), v.end(), output );
26

 2003 Prentice Hall, Inc.


All rights reserved.
90
27 // remove 10 from v
28 newLastElement = std::remove( v.begin(), v.end(), 10 );
Outline
29
30 cout << "\nVector v after removing all 10s:\n ";
Remove all 10's
fig21_28.cpp
from v.
31 std::copy( v.begin(), newLastElement, output );
Returns an iterator
(2 of 4)
pointing to
32
33 std::vector< int > v2( a, a + SIZE );
the new last element.
34 std::vector< int > c( SIZE, 0 );
35
36 cout << "\n\nVector v2 before removing all 10s "
37 << "and copying:\n "; Use remove_copy to create
38 std::copy( v2.begin(), v2.end(), output );
a duplicate of v, with all the
39
40 // copy from v2 to c, removing 10s in the process
10's removed.
41 std::remove_copy( v2.begin(), v2.end(), c.begin(), 10 );
42
43 cout << "\nVector c after removing all 10s from v2:\n ";
44 std::copy( c.begin(), c.end(), output );
45
46 std::vector< int > v3( a, a + SIZE );
47
48 cout << "\n\nVector v3 before removing all elements"
49 << "\ngreater than 9:\n ";
50 std::copy( v3.begin(), v3.end(), output );
51

 2003 Prentice Hall, Inc.


All rights reserved.
91
52 // remove elements greater than 9 from v3
53 newLastElement =
Outline
54 std::remove_if( v3.begin(), v3.end(), greater9 );
55
fig21_28.cpp
56 cout << "\nVector v3 after removing all elements" Use function greater9
(3 of 4) to
57 << "\ngreater than 9:\n "; determine whether to remove
58 std::copy( v3.begin(), newLastElement, output ); the element.
59
60 std::vector< int > v4( a, a + SIZE );
61 std::vector< int > c2( SIZE, 0 );
62
63 cout << "\n\nVector v4 before removing all elements"
64 << "\ngreater than 9 and copying:\n ";
65 std::copy( v4.begin(), v4.end(), output );
66 Note use of remove_copy_if.
67 // copy elements from v4 to c2, removing elements greater
68 // than 9 in the process
69 std::remove_copy_if(
70 v4.begin(), v4.end(), c2.begin(), greater9 );
71
72 cout << "\nVector c2 after removing all elements"
73 << "\ngreater than 9 from v4:\n ";
74 std::copy( c2.begin(), c2.end(), output );
75

 2003 Prentice Hall, Inc.


All rights reserved.
92
76 cout << endl;
77
Outline
78 return 0;
79
fig21_28.cpp
80 } // end main
(4 of 4)
81
82 // determine whether argument is greater than 9
83 bool greater9( int x )
84 {
85 return x > 9;
86
87 } // end greater9

 2003 Prentice Hall, Inc.


All rights reserved.
93
Vector v before removing all 10s:
10 2 10 4 16 6 14 8 12 10
Outline
Vector v after removing all 10s:
2 4 16 6 14 8 12
fig21_28.cpp
 
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
94
21.5.4 replace, replace_if, replace_copy and
replace_copy_if
• Functions
– replace( iter1, iter2, value, newvalue );
• Like remove, except replaces value with newvalue
– replace_if( iter1, iter2, function, newvalue );
• Replaces value if function returns true
– replace_copy(iter1, iter2, iter3, value,
newvalue);
• Replaces and copies elements to iter3
• Does not affect originals
– replace_copy_if( iter1, iter2, iter3, function,
newvalue );
• Replaces and copies elements to iter3 if function returns true

 2003 Prentice Hall, Inc. All rights reserved.


95
1 // Fig. 21.29: fig21_29.cpp
2 // Standard library functions replace, replace_if,
Outline
3 // replace_copy and replace_copy_if.
4 #include <iostream>
fig21_29.cpp
5
(1 of 4)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm>
10 #include <vector>
11
12 bool greater9( int );
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
19 std::ostream_iterator< int > output( cout, " " );
20
21 std::vector< int > v1( a, a + SIZE );
22 cout << "Vector v1 before replacing all 10s:\n ";
23 std::copy( v1.begin(), v1.end(), output );
24

 2003 Prentice Hall, Inc.


All rights reserved.
96
25 // replace 10s in v1 with 100
26 std::replace( v1.begin(), v1.end(), 10, 100 );
Outline
Use functions replace,
27 replace_copy.
28 cout << "\nVector v1 after replacing 10s with 100s:\n ";
fig21_29.cpp
29 std::copy( v1.begin(), v1.end(), output );
(2 of 4)
30
31 std::vector< int > v2( a, a + SIZE );
32 std::vector< int > c1( SIZE );
33
34 cout << "\n\nVector v2 before replacing all 10s "
35 << "and copying:\n ";
36 std::copy( v2.begin(), v2.end(), output );
37
38 // copy from v2 to c1, replacing 10s with 100s
39 std::replace_copy(
40 v2.begin(), v2.end(), c1.begin(), 10, 100 );
41
42 cout << "\nVector c1 after replacing all 10s in v2:\n ";
43 std::copy( c1.begin(), c1.end(), output );
44
45 std::vector< int > v3( a, a + SIZE );
46
47 cout << "\n\nVector v3 before replacing values greater"
48 << " than 9:\n ";
49 std::copy( v3.begin(), v3.end(), output );
50

 2003 Prentice Hall, Inc.


All rights reserved.
97
51 // replace values greater than 9 in v3 with 100
52 std::replace_if( v3.begin(), v3.end(), greater9, 100 );
Outline
53
54 cout << "\nVector v3 after replacing all values greater"
55 << "\nthan 9 with 100s:\n ";
fig21_29.cpp
56 std::copy( v3.begin(), v3.end(), output );
57
(3 of 4)
58 std::vector< int > v4( a, a + SIZE );
59 std::vector< int > c2( SIZE );
60
61 cout << "\n\nVector v4 before replacing all values greater "
62 << "than 9 and copying:\n ";
63 std::copy( v4.begin(), v4.end(), output );
64
65 // copy v4 to c2, replacing elements greater than 9 with 100
66 std::replace_copy_if(
67 v4.begin(), v4.end(), c2.begin(), greater9, 100 );
68
69 cout << "\nVector c2 after replacing all values greater "
70 << "than 9 in v4:\n ";
71 std::copy( c2.begin(), c2.end(), output );
72
73 cout << endl;
74
75 return 0;
76
77 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
98
78
79 // determine whether argument is greater than 9
Outline
80 bool greater9( int x )
81 {
82 return x > 9;
fig21_29.cpp
83
84 } // end function greater9
(4 of 4)

Vector v1 before replacing all 10s: fig21_29.cpp


10 2 10 4 16 6 14 8 12 10 output (1 of 1)
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
 2003 Prentice Hall, Inc.
All rights reserved.
99

21.5.5 Mathematical Algorithms

• random_shuffle(iter1, iter2)
– Randomly mixes elements in range
• count(iter1, iter2, value)
– Returns number of instances of value in range
• count_if(iter1, iter2, function)
– Counts number of instances that return true
• min_element(iter1, iter2)
– Returns iterator to smallest element
• max_element(iter1, iter2)
– Returns iterator to largest element

 2003 Prentice Hall, Inc. All rights reserved.


100

21.5.5 Mathematical Algorithms

• accumulate(iter1, iter2)
– Returns sum of elements in range
• for_each(iter1, iter2, function)
– Calls function on every element in range
– Does not modify element
• transform(iter1, iter2, iter3, function)
– Calls function for all elements in range of iter1-iter2,
copies result to iter3

 2003 Prentice Hall, Inc. All rights reserved.


101
1 // Fig. 21.30: fig21_30.cpp
2 // Mathematical algorithms of the standard library.
Outline
3 #include <iostream>
4
fig21_30.cpp
5 using std::cout;
(1 of 5)
6 using std::endl;
7
8 #include <algorithm> // algorithm definitions
9 #include <numeric> // accumulate is defined here
10 #include <vector>
11
12 bool greater9( int );
13 void outputSquare( int );
14 int calculateCube( int );
15
16 int main()
17 {
18 const int SIZE = 10;
19 int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
20
21 std::vector< int > v( a1, a1 + SIZE );
22 std::ostream_iterator< int > output( cout, " " );
23
24 cout << "Vector v before random_shuffle: ";
25 std::copy( v.begin(), v.end(), output );
26

 2003 Prentice Hall, Inc.


All rights reserved.
102
27 // shuffle elements of v
28 std::random_shuffle( v.begin(), v.end() );
Outline
29
30 cout << "\nVector v after random_shuffle: ";
fig21_30.cpp
31 std::copy( v.begin(), v.end(), output );
(2 of 5)
32
33 int a2[] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
34 std::vector< int > v2( a2, a2 + SIZE );
35
36 cout << "\n\nVector v2 contains: ";
37 std::copy( v2.begin(), v2.end(), output );
38
39 // count number of elements in v2 with value 8
40 int result = std::count( v2.begin(), v2.end(), 8 );
41
42 std::cout << "\nNumber of elements matching 8: " << result;
43
44 // count number of elements in v2 that are greater than 9
45 result = std::count_if( v2.begin(), v2.end(), greater9 );
46
47 cout << "\nNumber of elements greater than 9: " << result;
48

 2003 Prentice Hall, Inc.


All rights reserved.
103
49 // locate minimum element in v2
50 cout << "\n\nMinimum element in Vector v2 is: "
Outline
51 << *( std::min_element( v2.begin(), v2.end() ) );
52
fig21_30.cpp
53 // locate maximum element in v2
(3 of 5)
54 cout << "\nMaximum element in Vector v2 is: "
55 << *( std::max_element( v2.begin(), v2.end() ) );
56
57 // calculate sum of elements in v
58 cout << "\n\nThe total of the elements in Vector v is: "
59 << std::accumulate( v.begin(), v.end(), 0 );
60
61 cout << "\n\nThe square of every integer in Vector v is:\n";
62
63 // output square of every element in v
64 std::for_each( v.begin(), v.end(), outputSquare );
65
66 std::vector< int > cubes( SIZE );
67
68 // calculate cube of each element in v;
69 // place results in cubes
70 std::transform(
71 v.begin(), v.end(), cubes.begin(), calculateCube );

 2003 Prentice Hall, Inc.


All rights reserved.
104
72
73 cout << "\n\nThe cube of every integer in Vector v is:\n";
Outline
74 std::copy( cubes.begin(), cubes.end(), output );
75
fig21_30.cpp
76 cout << endl;
(4 of 5)
77
78 return 0;
79
80 } // end main
81
82 // determine whether argument is greater than 9
83 bool greater9( int value )
84 {
85 return value > 9;
86
87 } // end function greater9
88
89 // output square of argument
90 void outputSquare( int value )
91 {
92 cout << value * value << ' ';
93
94 } // end function outputSquare
95

 2003 Prentice Hall, Inc.


All rights reserved.
105
96 // return cube of argument
97 int calculateCube( int value )
Outline
98 {
99 return value * value * value;
fig21_30.cpp
100
(5 of 5)
101 } // end function calculateCube

Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10 fig21_30.cpp


Vector v after random_shuffle: 5 4 1 3 7 8 9 10 6 2 output (1 of 1)
 
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

 2003 Prentice Hall, Inc.


All rights reserved.
106

21.5.6 Basic Searching and Sorting Algorithms

• find(iter1, iter2, value)


– Returns iterator to first instance of value (in range)
• find_if(iter1, iter2, function)
– Like find
– Returns iterator when function returns true
• sort(iter1, iter2)
– Sorts elements in ascending order
• binary_search(iter1, iter2, value)
– Searches ascending sorted list for value
– Uses binary search

 2003 Prentice Hall, Inc. All rights reserved.


107
1 // Fig. 21.31: fig21_31.cpp
2 // Standard library search and sort algorithms.
Outline
3 #include <iostream>
4
fig21_31.cpp
5 using std::cout;
(1 of 4)
6 using std::endl;
7
8 #include <algorithm> // algorithm definitions
9 #include <vector> // vector class-template definition
10
11 bool greater10( int value ); // 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
18 std::vector< int > v( a, a + SIZE );
19 std::ostream_iterator< int > output( cout, " " );
20
21 cout << "Vector v contains: ";
22 std::copy( v.begin(), v.end(), output );
23
24 // locate first occurrence of 16 in v
25 std::vector< int >::iterator location;
26 location = std::find( v.begin(), v.end(), 16 );

 2003 Prentice Hall, Inc.


All rights reserved.
108
27
28 if ( location != v.end() )
Outline
29 cout << "\n\nFound 16 at location "
30 << ( location - v.begin() );
fig21_31.cpp
31 else
(2 of 4)
32 cout << "\n\n16 not found";
33
34 // locate first occurrence of 100 in v
35 location = std::find( v.begin(), v.end(), 100 );
36
37 if ( location != v.end() )
38 cout << "\nFound 100 at location "
39 << ( location - v.begin() );
40 else
41 cout << "\n100 not found";
42
43 // locate first occurrence of value greater than 10 in v
44 location = std::find_if( v.begin(), v.end(), greater10 );
45
46 if ( location != v.end() )
47 cout << "\n\nThe first value greater than 10 is "
48 << *location << "\nfound at location "
49 << ( location - v.begin() );
50 else
51 cout << "\n\nNo values greater than 10 were found";
52

 2003 Prentice Hall, Inc.


All rights reserved.
109
53 // sort elements of v
54 std::sort( v.begin(), v.end() );
Outline
55
56 cout << "\n\nVector v after sort: ";
fig21_31.cpp
57 std::copy( v.begin(), v.end(), output );
(3 of 4)
58
59 // use binary_search to locate 13 in v
60 if ( std::binary_search( v.begin(), v.end(), 13 ) )
61 cout << "\n\n13 was found in v";
62 else
63 cout << "\n\n13 was not found in v";
64
65 // use binary_search to locate 100 in v
66 if ( std::binary_search( v.begin(), v.end(), 100 ) )
67 cout << "\n100 was found in v";
68 else
69 cout << "\n100 was not found in v";
70
71 cout << endl;
72
73 return 0;
74
75 } // end main
76

 2003 Prentice Hall, Inc.


All rights reserved.
110
77 // determine whether argument is greater than 10
78 bool greater10( int value )
Outline
79 {
80 return value > 10;
fig21_31.cpp
81
(4 of 4)
82 } // end function greater10

Vector v contains: 10 2 17 5 16 8 13 11 20 7 fig21_31.cpp


  output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
111

21.5.7 swap, iter_swap and swap_ranges

• swap(element1, element2)
– Exchanges two values
– swap( a[ 0 ], a[ 1 ] );

• iter_swap(iter1, iter2)
– Exchanges the values to which the iterators refer

• swap_ranges(iter1, iter2, iter3)


– Swap the elements from iter1-iter2 with elements beginning
at iter3

 2003 Prentice Hall, Inc. All rights reserved.


112
1 // Fig. 21.32: fig21_32.cpp
2 // Standard library algorithms iter_swap, swap and swap_ranges.
Outline
3 #include <iostream>
4
fig21_32.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <algorithm> // algorithm definitions
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 );
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] "
23 << "using swap:\n ";
24 std::copy( a, a + SIZE, output );
25

 2003 Prentice Hall, Inc.


All rights reserved.
113
26 // use iterators to swap elements at locations
27 // 0 and 1 of array a
Outline
28 std::iter_swap( &a[ 0 ], &a[ 1 ] );
29 cout << "\nArray a after swapping a[0] and a[1] "
fig21_32.cpp
30 << "using iter_swap:\n ";
(2 of 2)
31 std::copy( a, a + SIZE, output );
32
33 // swap elements in first five elements of array a with
34 // elements in last five elements of array a
35 std::swap_ranges( a, a + 5, a + 5 );
36
37 cout << "\nArray a after swapping the first five elements\n"
38 << "with the last five elements:\n ";
39 std::copy( a, a + SIZE, output );
40
41 cout << endl;
42
43 return 0;
44
45 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
114
Array a contains:
1 2 3 4 5 6 7 8 9 10
Outline
Array a after swapping a[0] and a[1] using swap:
2 1 3 4 5 6 7 8 9 10
fig21_32.cpp
Array a after swapping a[0] and a[1] using iter_swap:
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
115

21.5.8 copy_backward, merge, unique and reverse

• copy_backward(iter1, iter2, iter3)


– Copy elements from iter1-iter2 to iter3, in reverse order
• merge(iter1, iter2, iter3, iter4, iter5)
– Ranges iter1-iter2 and iter3-iter4 must be sorted in
ascending order
– merge copies both lists into iter5, in ascending order
• unique(iter1, iter2)
– Removes duplicate elements from a sorted list
– Returns iterator to new end of sequence
• reverse(iter1, iter2)
– Reverses elements from iter1-iter2

 2003 Prentice Hall, Inc. All rights reserved.


116
1 // Fig. 21.33: fig21_33.cpp
2 // Standard library functions copy_backward, merge,
Outline
3 // unique and reverse.
4 #include <iostream>
fig21_33.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
11
12 int main()
13 {
14 const int SIZE = 5;
15 int a1[ SIZE ] = { 1, 3, 5, 7, 9 };
16 int a2[ SIZE ] = { 2, 4, 5, 7, 9 };
17
18 std::vector< int > v1( a1, a1 + SIZE );
19 std::vector< int > v2( a2, a2 + SIZE );
20
21 std::ostream_iterator< int > output( cout, " " );
22
23 cout << "Vector v1 contains: ";
24 std::copy( v1.begin(), v1.end(), output );
25 cout << "\nVector v2 contains: ";
26 std::copy( v2.begin(), v2.end(), output );

 2003 Prentice Hall, Inc.


All rights reserved.
117
27
28 std::vector< int > results( v1.size() );
Outline
29
30 // place elements of v1 into results in reverse order
fig21_33.cpp
31 std::copy_backward( v1.begin(), v1.end(), results.end() );
(2 of 3)
32
33 cout << "\n\nAfter copy_backward, results contains: ";
34 std::copy( results.begin(), results.end(), output );
35
36 std::vector< int > results2( v1.size() + v2.size() );
37
38 // merge elements of v1 and v2 into results2 in sorted order
39 std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(),
40 results2.begin() );
41
42 cout << "\n\nAfter merge of v1 and v2 results2 contains:\n";
43 std::copy( results2.begin(), results2.end(), output );
44
45 // eliminate duplicate values from results2
46 std::vector< int >::iterator endLocation;
47 endLocation =
48 std::unique( results2.begin(), results2.end() );
49
50 cout << "\n\nAfter unique results2 contains:\n";
51 std::copy( results2.begin(), endLocation, output );
52

 2003 Prentice Hall, Inc.


All rights reserved.
118
53 cout << "\n\nVector v1 after reverse: ";
54
Outline
55 // reverse elements of v1
56 std::reverse( v1.begin(), v1.end() );
57
fig21_33.cpp
58 std::copy( v1.begin(), v1.end(), output );
59
(3 of 3)
60 cout << endl;
61 fig21_33.cpp
62 return 0; output (1 of 1)
63
64 } // end main

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

 2003 Prentice Hall, Inc.


All rights reserved.
119
21.5.9 inplace_merge, unique_copy and
reverse_copy
• inplace_merge(iter1, iter2, iter3)
– Merges two sorted sequences (iter1-iter2, iter2-iter3)
inside the same container

• unique_copy(iter1, iter2, iter3)


– Copies all unique elements in sorted array (from iter1-iter2)
into iter3

• reverse_copy(iter1, iter2, iter3)


– Reverses elements in iter1-iter2, copies into iter3

 2003 Prentice Hall, Inc. All rights reserved.


120
1 // Fig. 21.34: fig21_34.cpp
2 // Standard library algorithms inplace_merge,
Outline
3 // reverse_copy and unique_copy.
4 #include <iostream>
fig21_34.cpp
5
(1 of 2)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
11 #include <iterator> // back_inserter definition
12
13 int main()
14 {
15 const int SIZE = 10;
16 int a1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 };
17 std::vector< int > v1( a1, a1 + SIZE );
18
19 std::ostream_iterator< int > output( cout, " " );
20
21 cout << "Vector v1 contains: ";
22 std::copy( v1.begin(), v1.end(), output );
23
24 // merge first half of v1 with second half of v1 such that
25 // v1 contains sorted set of elements after merge
26 std::inplace_merge( v1.begin(), v1.begin() + 5, v1.end() );
27

 2003 Prentice Hall, Inc.


All rights reserved.
121
28 cout << "\nAfter inplace_merge, v1 contains: ";
29 std::copy( v1.begin(), v1.end(), output );
Outline
30
31 std::vector< int > results1;
fig21_34.cpp
32
(2 of 2)
33 // copy only unique elements of v1 into results1
34 std::unique_copy(
35 v1.begin(), v1.end(), std::back_inserter( results1 ) );
36
37 cout << "\nAfter unique_copy results1 contains: ";
38 std::copy( results1.begin(), results1.end(), output );
39
40 std::vector< int > results2;
41
42 cout << "\nAfter reverse_copy, results2 contains: ";
43
44 // copy elements of v1 into results2 in reverse order
45 std::reverse_copy(
46 v1.begin(), v1.end(), std::back_inserter( results2 ) );
47
48 std::copy( results2.begin(), results2.end(), output );
49
50 cout << endl;
51
52 return 0;
53
54 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
122
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
Outline
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
fig21_34.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
123

21.5.10 Set Operations

• includes(iter1, iter2, iter3, iter4)


– Returns true if iter1-iter2 contains iter3-iter4
– Both ranges must be sorted
a1: 1 2 3 4
a2: 1 3
a1 includes a3
• set_difference(iter1, iter2, iter3, iter4,
iter5)
– Copies elements in first set (1-2) that are not in second set (3-4)
into iter5
• set_intersection(iter1, iter2, iter3,
iter4, iter5)
– Copies common elements from the two sets (1-2, 3-4) into iter5

 2003 Prentice Hall, Inc. All rights reserved.


124

21.5.10 Set Operations

• set_symmetric_difference(iter1, iter2,
iter3, iter4, iter5)
– Copies elements in set (1-2) but not set (3-4), and vice versa, into
iter5
• a1: 1 2 3 4 5 6 7 8 9 10
• a2: 4 5 6 7 8
• set_symmetric_difference: 1 2 3 9 10
– Both sets must be sorted

• set_union( iter1, iter2, iter3, iter4,


iter5)
– Copies elements in either or both sets to iter5
– Both sets must be sorted

 2003 Prentice Hall, Inc. All rights reserved.


125
1 // Fig. 21.35: fig21_35.cpp
2 // Standard library algorithms includes, set_difference,
Outline
3 // set_intersection, set_symmetric_difference and set_union.
4 #include <iostream>
fig21_35.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm> // algorithm definitions
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 );
21 cout << "\na2 contains: ";
22 std::copy( a2, a2 + SIZE2, output );
23 cout << "\na3 contains: ";
24 std::copy( a3, a3 + SIZE2, output );
25

 2003 Prentice Hall, Inc.


All rights reserved.
126
26 // determine whether set a2 is completely contained in a1
27 if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) )
Outline
28 cout << "\n\na1 includes a2";
29 else
fig21_35.cpp
30 cout << "\n\na1 does not include a2";
(2 of 3)
31
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
44 cout << "\n\nset_difference of a1 and a2 is: ";
45 std::copy( difference, ptr, output );
46
47 int intersection[ SIZE1 ];
48
49 // determine elements in both a1 and a2
50 ptr = std::set_intersection( a1, a1 + SIZE1,
51 a2, a2 + SIZE2, intersection );
52

 2003 Prentice Hall, Inc.


All rights reserved.
127
53 cout << "\n\nset_intersection of a1 and a2 is: ";
54 std::copy( intersection, ptr, output );
Outline
55
56 int symmetric_difference[ SIZE1 ];
fig21_35.cpp
57
(3 of 3)
58 // determine elements of a1 that are not in a2 and
59 // elements of a2 that are not in a1
60 ptr = std::set_symmetric_difference( a1, a1 + SIZE1,
61 a2, a2 + SIZE2, symmetric_difference );
62
63 cout << "\n\nset_symmetric_difference of a1 and a2 is: ";
64 std::copy( symmetric_difference, ptr, output );
65
66 int unionSet[ SIZE3 ];
67
68 // determine elements that are in either or both sets
69 ptr = std::set_union( a1, a1 + SIZE1,
70 a3, a3 + SIZE2, unionSet );
71
72 cout << "\n\nset_union of a1 and a3 is: ";
73 std::copy( unionSet, ptr, output );
74
75 cout << endl;
76
77 return 0;
78
79 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
128
a1 contains: 1 2 3 4 5 6 7 8 9 10
a2 contains: 4 5 6 7 8
Outline
a3 contains: 4 5 6 11 15
 
fig21_35.cpp
a1 includes a2
output (1 of 1)
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 a2 is: 1 2 3 9 10
 
set_union of a1 and a3 is: 1 2 3 4 5 6 7 8 9 10 11 15

 2003 Prentice Hall, Inc.


All rights reserved.
129
21.5.11 lower_bound, upper_bound and
equal_range
• lower_bound(iter1, iter2, value)
– For sorted elements, returns iterator to the first location where
value could be inserted and elements remain sorted
• upper_bound(iter1, iter2, value)
– Same as lower_bound, but returns iterator to last element where
value could be inserted
• equal_range(iter1, iter2, value)
– Returns two iterators, a lower_bound and an upper_bound
– Assign them to a pair object

 2003 Prentice Hall, Inc. All rights reserved.


130
1 // Fig. 21.36: fig21_36.cpp
2 // Standard library functions lower_bound, upper_bound and
Outline
3 // equal_range for a sorted sequence of values.
4 #include <iostream>
5
fig21_36.cpp
6 using std::cout;
7 using std::endl;
(1 of 4)
8
9 #include <algorithm> // algorithm definitions
10 #include <vector> // vector class-template definition
11
12 int main()
13 {
14 const int SIZE = 10;
15 int a1[] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 };
16 std::vector< int > v( a1, a1 + SIZE );
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

 2003 Prentice Hall, Inc.


All rights reserved.
131
26 cout << "\n\nLower bound of 6 is element "
27 << ( lower - v.begin() ) << " of vector v";
Outline
28
29 // determine upper-bound insertion point for 6 in v
30 std::vector< int >::iterator upper;
fig21_36.cpp
31 upper = std::upper_bound( v.begin(), v.end(), 6 );
32
(2 of 4)
33 cout << "\nUpper bound of 6 is element "
34 << ( upper - v.begin() ) << " of vector v";
35
36 // use equal_range to determine both the lower- and
37 // upper-bound insertion points for 6
38 std::pair< std::vector< int >::iterator,
39 std::vector< int >::iterator > eq;
40 eq = std::equal_range( v.begin(), v.end(), 6 );
41
42 cout << "\nUsing equal_range:\n"
43 << " Lower bound of 6 is element "
44 << ( eq.first - v.begin() ) << " of vector v";
45 cout << "\n Upper bound of 6 is element "
46 << ( eq.second - v.begin() ) << " of vector v";
47
48 cout << "\n\nUse lower_bound to locate the first point\n"
49 << "at which 5 can be inserted in order";
50

 2003 Prentice Hall, Inc.


All rights reserved.
132
51 // determine lower-bound insertion point for 5 in v
52 lower = std::lower_bound( v.begin(), v.end(), 5 );
Outline
53
54 cout << "\n Lower bound of 5 is element "
55 << ( lower - v.begin() ) << " of vector v";
56
57 cout << "\n\nUse upper_bound to locate the last point\n"
fig21_36.cpp
58 << "at which 7 can be inserted in order"; (3 of 4)
59
60 // determine upper-bound insertion point for 7 in v
61 upper = std::upper_bound( v.begin(), v.end(), 7 );
62
63 cout << "\n Upper bound of 7 is element "
64 << ( upper - v.begin() ) << " of vector v";
65
66 cout << "\n\nUse equal_range to locate the first and\n"
67 << "last point at which 5 can be inserted in order";
68
69 // use equal_range to determine both the lower- and
70 // upper-bound insertion points for 5
71 eq = std::equal_range( v.begin(), v.end(), 5 );
72
73 cout << "\n Lower bound of 5 is element "
74 << ( eq.first - v.begin() ) << " of vector v";
75 cout << "\n Upper bound of 5 is element "
76 << ( eq.second - v.begin() ) << " of vector v"
77 << endl;

 2003 Prentice Hall, Inc.


All rights reserved.
133
78
79 return 0;
Outline
80
81 } // end main
fig21_36.cpp
Vector v contains: (4 of 4)
2 2 4 4 4 6 6 6 6 8
  fig21_36.cpp
Lower bound of 6 is element 5 of vector v output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
134

21.5.12 Heapsort

• Heapsort - sorting algorithm


– Heap binary tree
– Largest element at top of heap
– Children always less than parent node
– make_heap(iter1, iter2)
• Creates a heap in the range of the iterators
• Must be random access iterators (arrays, vectors, deques)
– sort_heap(iter1, iter2)
• Sorts a heap sequence from iter1 to iter2

 2003 Prentice Hall, Inc. All rights reserved.


135

21.5.12 Heapsort

• Functions
– push_heap(iter1, iter2)
• The iterators must specify a heap
• Adds last element in object to heap
– Assumes other elements already in heap order
– pop_heap(iter1, iter2)
• Removes the top element of a heap and puts it at the end of the
container.
• Function checks that all other elements still in a heap
• Range of the iterators must be a heap.
• If all the elements popped, sorted list

 2003 Prentice Hall, Inc. All rights reserved.


136
1 // Fig. 21.37: fig21_37.cpp
2 // Standard library algorithms push_heap, pop_heap,
Outline
3 // make_heap and sort_heap.
4 #include <iostream>
fig21_37.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <algorithm>
10 #include <vector>
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 ), v2;
17 std::ostream_iterator< int > output( cout, " " );
18
19 cout << "Vector v before make_heap:\n";
20 std::copy( v.begin(), v.end(), output );
Create a new heap.
21
22 // create heap from vector v
23 std::make_heap( v.begin(), v.end() );
24
25 cout << "\nVector v after make_heap:\n";
26 std::copy( v.begin(), v.end(), output );

 2003 Prentice Hall, Inc.


All rights reserved.
137
27
28 // sort elements of v with sort_heap
Outline
29 std::sort_heap( v.begin(), v.end() );
30
fig21_37.cpp
31 cout << "\nVector v after sort_heap:\n";
(2 of 3)
32 std::copy( v.begin(), v.end(), output );
33
34 // perform the heapsort with push_heap and pop_heap
35 cout << "\n\nArray a contains: ";
36 std::copy( a, a + SIZE, output );
37
38 cout << endl;
39
40 // place elements of array a into v2 and Add elements one at a time.
41 // maintain elements of v2 in heap
42 for ( int i = 0; i < SIZE; ++i ) {
43 v2.push_back( a[ i ] );
44 std::push_heap( v2.begin(), v2.end() );
45 cout << "\nv2 after push_heap(a[" << i << "]): ";
46 std::copy( v2.begin(), v2.end(), output );
47
48 } // end for
49
50 cout << endl;
51

 2003 Prentice Hall, Inc.


All rights reserved.
138
52 // remove elements from heap in sorted order
53 for ( int j = 0; j < v2.size(); ++j ) {
Outline
54 cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";
55 std::pop_heap( v2.begin(), v2.end() - j );
56 std::copy( v2.begin(), v2.end(), output );
fig21_37.cpp
57
58 } // end for
(3 of 3)
59
60 cout << endl;
61
62 return 0;
63
64 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
139
Vector v before make_heap:
3 100 52 77 22 31 1 98 13 40
Outline
Vector v after make_heap:
100 98 52 77 40 31 1 3 13 22
fig21_37.cpp
Vector v after sort_heap:
output (1 of 2)
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

 2003 Prentice Hall, Inc.


All rights reserved.
140
v2 after 100 popped from heap
98 77 52 22 40 31 1 3 13 100
Outline
v2 after 98 popped from heap
77 40 52 22 13 31 1 3 98 100
fig21_37.cpp
v2 after 77 popped from heap
output (2 of 2)
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

 2003 Prentice Hall, Inc.


All rights reserved.
141

21.5.13 min and max

• min(value1, value2)
– Returns smaller element
• max(value1, value2)
– Returns larger element

 2003 Prentice Hall, Inc. All rights reserved.


142
1 // Fig. 21.38: fig21_38.cpp
2 // Standard library algorithms min and max.
Outline
3 #include <iostream>
4
fig21_38.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <algorithm>
9
10 int main()
11 {
12 cout << "The minimum of 12 and 7 is: "
13 << std::min( 12, 7 );
14 cout << "\nThe maximum of 12 and 7 is: "
15 << std::max( 12, 7 );
16 cout << "\nThe minimum of 'G' and 'Z' is: "
17 << std::min( 'G', 'Z' );
18 cout << "\nThe maximum of 'G' and 'Z' is: "
19 << std::max( 'G', 'Z' ) << endl;
20
21 return 0;
22
23 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
143
The minimum of 12 and 7 is: 7
The maximum of 12 and 7 is: 12
Outline
The minimum of 'G' and 'Z' is: G
The maximum of 'G' and 'Z' is: Z
fig21_38.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
144

21.5.14 Algorithms Not Covered in This Chapter

• adjacent_difference
• inner_product
• partial_sum
• nth_element
• partition
• stable_partition
• next_permutation
• prev_permutation
• rotate
• rotate_copy
• adjacent_find
• partial_sort
• partial_sort_copy
• stable_sort

 2003 Prentice Hall, Inc. All rights reserved.


145

21.6 Class bitset

• Class bitset
– Represents a set of bit flags
– Can manipulate bit sets
• Operations
– bitset <size> b; create bitset
– b.set( bitNumber) set bit bitNumber to on
– b.set() all bits on
– b.reset(bitNumber) set bit bitNumber to off
– b.reset() all bits off
– b.flip(bitNumber) flip bit (on to off, off to on)
– b.flip() flip all bits
– b[bitNumber] returns reference to bit
– b.at(bitNumber) range checking, returns reference

 2003 Prentice Hall, Inc. All rights reserved.


146

21.6 Class bitset

• Operations
• b.test(bitNumber) has range checking; if bit on, returns true
• b.size() size of bitset
• b.count() number of bits set to on
• b.any() true if any bits are on
• b.none() true if no bits are on
• can use &=, |=, !=, <<=, >>=
– b &= b1
– Logical AND between b and b1, result in b
• b.to_string() convert to string
• b.to_ulong() convert to long

 2003 Prentice Hall, Inc. All rights reserved.


147
1 // Fig. 21.40: fig21_40.cpp
2 // Using a bitset to demonstrate the Sieve of Eratosthenes.
Outline
3 #include <iostream>
4
fig21_40.cpp
5 using std::cin;
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 #include <bitset> // bitset class definition
14 #include <cmath> // sqrt prototype
15
16 int main()
17 {
18 const int size = 1024;
19 int value;
20 std::bitset< size > sieve;
21
22 sieve.flip();
23

 2003 Prentice Hall, Inc.


All rights reserved.
148
24 // perform Sieve of Eratosthenes
25 int finalBit = sqrt( sieve.size() ) + 1; Sieve of Eratosthenes: turn offOutline
26 bits for all multiples of a
27 for ( int i = 2; i < finalBit; ++i ) number. What bits remain are
fig21_40.cpp
28 prime. (2 of 3)
29 if ( sieve.test( i ) )
30
31 for ( int j = 2 * i; j < size; j += i )
32 sieve.reset( j );
33
34 cout << "The prime numbers in the range 2 to 1023 are:\n";
35
36 // display prime numbers in range 2-1023
37 for ( int k = 2, counter = 0; k < size; ++k )
38
39 if ( sieve.test( k ) ) {
40 cout << setw( 5 ) << k;
41
42 if ( ++counter % 12 == 0 )
43 cout << '\n';
44
45 } // end outer if
46
47 cout << endl;
48

 2003 Prentice Hall, Inc.


All rights reserved.
149
49 // get value from user to determine whether value is prime
50 cout << "\nEnter a value from 1 to 1023 (-1 to end): ";
Outline
51 cin >> value;
52
fig21_40.cpp
53 while ( value != -1 ) {
(3 of 3)
54
55 if ( sieve[ value ] )
56 cout << value << " is a prime number\n";
57 else
58 cout << value << " is not a prime number\n";
59
60 cout << "\nEnter a value from 2 to 1023 (-1 to end): ";
61 cin >> value;
62
63 } // end while
64
65 return 0;
66
67 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
150
The prime numbers in the range 2 to 1023 are:
2 3 5 7 11 13 17 19 23 29 31 37
Outline
41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149 151
fig21_40.cpp
157 163 167 173 179 181 191 193 197 199 211 223
output (1 of 1)
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 1 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

 2003 Prentice Hall, Inc.


All rights reserved.
151

21.7 Function Objects

• Function objects (<functional>)


– Contain functions invoked using operator()
STL fu n c tio n o b je c ts Typ e
divides< T > arithmetic
equal_to< T > relational
greater< T > relational
greater_equal< T > relational
less< T > relational
less_equal< T > relational
logical_and< T > logical
logical_not< T > logical
logical_or< T > logical
minus< T > arithmetic
modulus< T > arithmetic
negate< T > arithmetic
not_equal_to< T > relational
plus< T > arithmetic
multiplies< T > arithmetic

 2003 Prentice Hall, Inc. All rights reserved.


152
1 // Fig. 21.42: fig21_42.cpp
2 // Demonstrating function objects.
Outline
3 #include <iostream>
4
5 using std::cout;
fig21_42.cpp
6 using std::endl;
7
(1 of 4)
8 #include <vector> // vector class-template definition
9 #include <algorithm> // copy algorithm
10 #include <numeric> // accumulate algorithm
11 #include <functional> // binary_function definition
12 Create a function to be used
13 // binary function adds square of its second argument andwith accumulate.
14 // running total in its first argument, then returns sum
15 int sumSquares( int total, int value )
16 {
17 return total + value * value;
18
19 } // end function sumSquares
20

 2003 Prentice Hall, Inc.


All rights reserved.
153
21 // binary function class template defines overloaded operator()
22 // that adds suare of its second argument and running total in
Outline
23 // its first argument, then returns sum
24 template< class T >
25 class SumSquaresClass : public std::binary_function< T, T, T > {
fig21_42.cpp
26
Create a function (2
object
of 4)(it
27 public:
28
can also encapsulate data).
29 // add square of value to total and return result Overload operator().
30 const T operator()( const T &total, const T &value )
31 {
32 return total + value * value;
33
34 } // end function operator()
35
36 }; // end class SumSquaresClass
37

 2003 Prentice Hall, Inc.


All rights reserved.
154
38 int main()
39 {
Outline
40 const int SIZE = 10;
41 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
42
fig21_42.cpp
43 std::vector< int > integers( array, array + SIZE );
44
(3 of 4)
45 std::ostream_iterator< int > output( cout, " " );
46
47 int result = 0;
48 accumulate initially passes
49 cout << "vector v contains:\n"; 0 as the first argument, with
50 std::copy( integers.begin(), integers.end(), output );
the first element as the
51
second. It then uses the return
52 // calculate sum of squares of elements of vector integers
53 // using binary function sumSquares
value as the first argument,
54 result = std::accumulate( integers.begin(), integers.end(), and iterates through the other
55 0, sumSquares ); elements.
56
57 cout << "\n\nSum of squares of elements in integers using "
58 << "binary\nfunction sumSquares: " << result;
59

 2003 Prentice Hall, Inc.


All rights reserved.
155
60 // calculate sum of squares of elements of vector integers
61 // using binary-function object
Outline
62 result = std::accumulate( integers.begin(), integers.end(),
63 0, SumSquaresClass< int >() );
fig21_42.cpp
64
(4 of 4)
65 cout << "\n\nSum of squares of elements in integers using "
66 << "binary\nfunction object of type "
67 << "SumSquaresClass< int >: " << result << endl; fig21_42.cpp
68 output (1 of 1)
69 return 0; Use accumulate with a
70 function object.
71 } // end main

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

 2003 Prentice Hall, Inc.


All rights reserved.

You might also like