Chapter 21 Standard Template Library STL Outline 21
Chapter 21 - Standard Template Library (STL) Outline 21. 1 21. 2 21. 3 21. 4 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 Sequence Containers 21. 2. 1 vector Sequence Container 21. 2. 2 list Sequence Container 21. 2. 3 deque Sequence Container 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 Adapters 21. 4. 1 stack Adapter 21. 4. 2 queue Adapter 21. 4. 3 priority_queue Adapter 1
Chapter 21 - Standard Template Library (STL) 21. 5 21. 6 21. 7 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 Class bitset Function Objects 2
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 – Only an introduction to STL, a huge class library 3
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: stack, queue, and priority_queue • Near containers – Similar to containers, with reduced functionality – C-like pointer-based arrays, strings, bitsets, and valarrays • Containers have some common functions
5 STL Container Classes (Fig. 21. 1) • Sequence containers – vector – deque – list • Associative containers – – set multiset map multimap • Container adapters – stack – queue – priority_queue
6 Common STL Member Functions (Fig. 21. 2) • Member functions for all containers – – – Default constructor, copy constructor, destructor empty size = < <= > >= == != swap • Functions for first-class containers – – max_size, begin, end rbegin, rend erase, clear
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
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
9 21. 1. 2 Introduction to Iterators • Usage – std: : istream_iterator< int > input. Int( cin ) • Can read input from cin • *input. Int – Dereference to read first int from cin • ++input. Int – Go to next in stream – std: : ostream_iterator< int > output. Int(cout) • Can output ints to cout • *output. Int = 7 – Outputs 7 to cout • ++output. Int – Advances iterator so we can output next int
1 2 3 // Fig. 21. 5: fig 21_05. cpp // Demonstrating input and output with iterators. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 #include <iterator> 10 11 12 13 int main() { cout << "Enter two Note creation of istream_iterator. For compilation reasons, we use std: : rather than a using integers: "; statement. // ostream_iterator and istream_iterator 14 15 16 // create istream_iterator for reading int values from cin std: : istream_iterator< int > input. Int( cin ); 17 18 19 20 int number 1 = *input. Int; // read int from standard input ++input. Int; // move iterator to next input value int number 2 = *input. Int; // read int from standard input 21 10 fig 21_05. cpp Access and assign (1 of 2)the iterator like a pointer.
22 23 // create ostream_iterator for writing int values to cout std: : ostream_iterator< int > output. Int( cout ); 24 25 26 27 cout << "The sum is: "; *output. Int = number 1 + number 2; cout << endl; 28 29 return 0; 30 31 11 // output result to cout } // end main Enter two integers: 12 25 Create an The sum is: 37 ostream_iterator is similar. Assigning to this iterator outputs to cout. fig 21_05. cpp (2 of 2) fig 21_05. cpp output (1 of 1)
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
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
14 Iterator Operations (Fig. 21. 10) • All – ++p, p++ • Input iterators – *p – p = p 1 – p == p 1, p != p 1 • Output iterators – *p – p = p 1 • Forward iterators – Have functionality of input and output iterators
15 Iterator Operations (Fig. 21. 10) • Bidirectional – --p, p-- • Random access – – – p + i, p += i p - i, p -= i p[i] p < p 1, p <= p 1 p > p 1, p >= p 1
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
17 21. 2 Sequence Containers • Three sequence containers – vector - based on arrays – deque - based on arrays – list - robust linked list
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
19 21. 2. 1 vector Sequence Container • Declarations – std: : vector <type> v; • type: int, float, etc. • Iterators – std: : vector<type>: : const_iterator iter. Var; • const_iterator cannot modify elements – std: : vector<type>: : reverse_iterator iter. Var; • Visits elements in reverse order (end to beginning) • Use rbegin to get starting point • Use rend to get ending point
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
21 21. 2. 1 vector Sequence Container • vector functions – v. insert(iterator, value ) • Inserts value before location of iterator – v. insert(iterator, array + SIZE) • Inserts array elements (up to, but not including array + SIZE) into vector – v. erase( iterator ) • Remove element from container – v. erase( iter 1, iter 2 ) • Remove elements starting from iter 1 and up to (not including) iter 2 – v. clear() • Erases entire container
22 21. 2. 1 vector Sequence Container • vector functions operations – v. front(), v. back() • Return first and last element – v. [element. Number] = value; • Assign value to an element – v. at[element. Number] = value; • As above, with range checking • out_of_bounds exception
23 21. 2. 1 vector Sequence Container • ostream_iterator – std: : ostream_iterator< type > Name( output. Stream, separator ); • type: outputs values of a certain type • output. Stream: iterator output location • separator: character separating outputs • Example – std: : ostream_iterator< int > output( cout, " " ); – std: : copy( iterator 1, iterator 2, output ); • Copies elements from iterator 1 up to (not including) iterator 2 to output, an ostream_iterator
1 2 3 // Fig. 21. 14: fig 21_14. cpp // Demonstrating standard library vector class template. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 #include <vector> 10 11 12 13 // prototype for function template print. Vector template < class T > void print. Vector( const std: : vector< T > &integers 2 ); 14 15 16 17 18 int main() { Create a const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; // vector class-template definition 19 20 std: : vector< int > integers; 21 22 23 24 25 cout << << 26 24 vector of ints. Call member functions. "The initial size of integers is: " integers. size() "n. The initial capacity of integers is: " integers. capacity(); fig 21_14. cpp (1 of 3)
25 27 28 29 30 // function push_back integers. push_back( 2 integers. push_back( 3 integers. push_back( 4 31 32 33 34 cout << "n. The size of integers is: " << integers. size() << "n. The capacity of integers is: " << integers. capacity(); 35 36 cout << "nn. Output array using pointer notation: " ; 37 38 39 for ( int *ptr = array; ptr != array + SIZE; ++ptr ) cout << *ptr << ' '; 40 41 42 cout << "n. Output vector using iterator notation: " ; print. Vector( integers ); 43 44 cout << "n. Reversed contents of vector integers: " ; 45 is in every sequence collection ); ); ); Add elements to end of vector using push_back. fig 21_14. cpp (2 of 3)
46 std: : vector< int >: : reverse_iterator reverse. Iterator; 47 48 49 50 51 for ( reverse. Iterator = integers. rbegin(); reverse. Iterator!= integers. rend(); ++reverse. Iterator ) cout << *reverse. Iterator << ' '; 52 53 cout << endl; 54 55 return 0; 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 } // end main // function template for outputting vector elements template < class T > void print. Vector( const std: : vector< T > &integers 2 ) { std: : vector< T >: : const_iterator const. Iterator; for ( const. Iterator = integers 2. begin(); const. Iterator != integers 2. end(); const. Iterator++ ) cout << *const. Iterator << ' '; } // end function print. Vector 26 Walk through vector backwards using a reverse_iterator. Template function to walk fig 21_14. cpp through vector forwards. (3 of 3)
The The 27 initial size of v is: 0 initial capacity of v is: 0 size of v is: 3 capacity of v is: 4 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 fig 21_14. cpp output (1 of 1)
1 2 3 4 // Fig. 21. 15: fig 21_15. cpp // Testing Standard Library vector class template // element-manipulation functions. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <vector> #include <algorithm> 11 12 13 14 15 int main() { const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; 28 // vector class-template definition // copy algorithm fig 21_15. cpp Create vector (initialized (1 of 3) using an array) and ostream_iterator. 16 17 18 std: : vector< int > integers( array, array + SIZE ); std: : ostream_iterator< int > output( cout, " " ); 19 20 21 cout << "Vector integers contains: " ; std: : copy( integers. begin(), integers. end(), output ); 22 23 24 cout << "n. First element of integers: " << integers. front() << "n. Last element of integers: " << integers. back(); 25 Copy range of iterators to output (ostream_iterator).
26 27 integers[ 0 ] = 7; integers. at( 2 ) = 10; 28 29 30 // insert 22 as 2 nd element integers. insert( integers. begin() + 1, 22 ); 31 32 33 cout << "nn. Contents of vector integers after changes: " ; std: : copy( integers. begin(), integers. end(), output ); 34 35 36 37 // access out-of-range element try { integers. at( 100 ) = 777; More vector member functions. at has range checking, and can throw an exception. 38 39 } // end try 40 41 42 43 // catch out_of_range exception catch ( std: : out_of_range out. Of. Range ) { cout << "nn. Exception: " << out. Of. Range. what(); 44 45 } // end catch 46 47 48 49 50 // erase first element integers. erase( integers. begin() ); cout << "nn. Vector integers after erasing first element: " ; std: : copy( integers. begin(), integers. end(), output ); 51 29 // set first element to 7 // set element at position 2 to 10 fig 21_15. cpp (2 of 3)
52 53 54 55 // erase remaining elements integers. erase( integers. begin(), integers. end() ); cout << "n. After erasing all elements, vector integers " << ( integers. empty() ? "is" : "is not" ) << " empty"; 56 57 58 59 60 // insert elements from array integers. insert( integers. begin(), array + SIZE ); cout << "nn. Contents of vector integers before clear: " ; std: : copy( integers. begin(), integers. end(), output ); 61 62 63 64 65 // empty integers; clear calls erase to empty a collection integers. clear(); cout << "n. After clear, vector integers " << ( integers. empty() ? "is" : "is not" ) << " empty"; 66 67 cout << endl; 68 69 return 0; 70 71 } // end main 30 fig 21_15. cpp (3 of 3)
31 Vector integers contains: 1 2 3 4 5 6 First element of integers: 1 Last element of integers: 6 Contents of vector integers after changes: 7 22 2 10 4 5 6 Exception: invalid vector<T> subscript Vector integers after erasing first element: 22 2 10 4 5 6 After erasing all elements, vector integers is empty Contents of vector integers before clear: 1 2 3 4 5 6 After clear, vector integers is empty fig 21_15. cpp output (1 of 1)
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;
33 21. 2. 2 list Sequence Container • list functions for object t – t. sort() • Sorts in ascending order – t. splice(iterator, other. Object ); • Inserts values from other. Object before iterator – t. merge( other. Object ) • Removes other. Object and inserts it into t, sorted – t. unique() • Removes duplicate elements
34 21. 2. 2 list Sequence Container • list functions – t. swap(other. Object); • Exchange contents – t. assign(iterator 1, iterator 2) • Replaces contents with elements in range of iterators – t. remove(value) • Erases all instances of value
1 2 3 // Fig. 21. 17: fig 21_17. cpp // Standard library list class template test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <list> #include <algorithm> 10 11 12 13 // prototype for function template print. List template < class T > void print. List( const std: : list< T > &list. Ref ); 14 15 16 17 18 int main() { const int SIZE = 4; int array[ SIZE ] = { 2, 6, 4, 8 }; 35 // list class-template definition // copy algorithm 19 20 21 std: : list< int > values; std: : list< int > other. Values; 22 23 24 25 26 27 // insert items in values. push_front( 1 ); values. push_front( 2 ); values. push_back( 4 ); values. push_back( 3 ); Create two list objects. fig 21_17. cpp (1 of 5)
36 28 29 30 cout << "values contains: "; print. List( values ); 31 32 values. sort(); 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 Various list member functions. // sort values cout << "nvalues after sorting contains: " ; print. List( values ); // insert elements of array into other. Values. insert( other. Values. begin(), array + SIZE ); cout << "n. After insert, other. Values contains: "; print. List( other. Values ); // remove other. Values elements and insert at end of values. splice( values. end(), other. Values ); cout << "n. After splice, values contains: " ; print. List( values ); 49 50 values. sort(); 51 52 53 cout << "n. After sort, values contains: " ; print. List( values ); 54 // sort values fig 21_17. cpp (2 of 5)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 37 // insert elements of array into other. Values. insert( other. Values. begin(), array + SIZE ); other. Values. sort(); cout << "n. After insert, other. Values contains: "; print. List( other. Values ); // remove other. Values elements and insert into values // in sorted order values. merge( other. Values ); cout << "n. After merge: n values contains: " ; print. List( values ); cout << "n other. Values contains: "; print. List( other. Values ); values. pop_front(); values. pop_back(); // remove element from front // remove element from back cout << "n. After pop_front and pop_back: " << "n values contains: " ; print. List( values ); values. unique(); // remove duplicate elements cout << "n. After unique, values contains: " ; print. List( values ); fig 21_17. cpp (3 of 5)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 38 // swap elements of values and other. Values values. swap( other. Values ); cout << "n. After swap: n values contains: " ; print. List( values ); cout << "n other. Values contains: "; print. List( other. Values ); // replace contents of values with elements of other. Values values. assign( other. Values. begin(), other. Values. end() ); cout << "n. After assign, values contains: " ; print. List( values ); // remove other. Values elements and insert into values // in sorted order values. merge( other. Values ); cout << "n. After merge, values contains: " ; print. List( values ); values. remove( 4 ); // remove all 4 s cout << "n. After remove( 4 ), values contains: " ; print. List( values ); fig 21_17. cpp (4 of 5)
39 109 110 cout << endl; 111 112 return 0; 113 114 } // end main 115 116 117 118 119 120 121 122 // print. List function template definition; uses // ostream_iterator and copy algorithm to output list elements template < class T > void print. List( const std: : list< T > &list. Ref ) { if ( list. Ref. empty() ) cout << "List is empty"; 123 124 125 126 else { std: : ostream_iterator< T > output( cout, " " ); std: : copy( list. Ref. begin(), list. Ref. end(), output ); 127 128 } // end else 129 130 } // end function print. List fig 21_17. cpp (5 of 5)
values contains: 2 1 4 3 values after sorting contains: 1 2 3 4 After insert, other. Values contains: 2 6 4 8 After splice, values contains: 1 2 3 4 2 6 4 8 After sort, values contains: 1 2 2 3 4 4 6 8 After insert, other. Values contains: 2 4 6 8 After merge: values contains: 1 2 2 2 3 4 4 4 6 6 8 8 other. Values 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 other. Values 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 40 fig 21_17. cpp output (1 of 1)
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)
1 2 3 // Fig. 21. 18: fig 21_18. cpp // Standard library class deque test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <deque> #include <algorithm> 10 11 12 13 14 int main() { std: : deque< double > values; std: : ostream_iterator< double > output( cout, " " ); // deque class-template definition // copy algorithm Create a deque, use member functions. 15 16 17 18 19 // insert elements in values. push_front( 2. 2 ); values. push_front( 3. 5 ); values. push_back( 1. 1 ); 20 21 cout << "values contains: "; 22 23 24 25 // use subscript operator to obtain elements of values for ( int i = 0; i < values. size(); ++i ) cout << values[ i ] << ' '; 26 42 fig 21_18. cpp (1 of 2)
27 values. pop_front(); 28 29 30 cout << "n. After pop_front, values contains: " ; std: : copy( values. begin(), values. end(), output ); 31 32 33 // use subscript operator to modify element at location 1 values[ 1 ] = 5. 4; 34 35 36 37 38 39 40 41 42 43 // remove first element cout << "n. After values[ 1 ] = 5. 4, values contains: " ; std: : copy( values. begin(), values. end(), output ); cout << endl; return 0; } // 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 fig 21_18. cpp (2 of 2) fig 21_18. cpp output (1 of 1)
44 21. 3 Associative Containers • Associative containers – Direct access to store/retrieve elements – Uses keys (search keys) – 4 types: multiset, 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
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> > my. Object; • Elements will be sorted in ascending order
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
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
48 1 2 3 // Fig. 21. 19: fig 21_19. cpp // Testing Standard Library class multiset #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <set> 9 10 11 // define short name for multiset type used in typedef std: : multiset< int, std: : less< int > > 12 13 #include <algorithm> 14 15 16 17 18 int main() { const int SIZE = 10; int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 }; 19 20 21 22 23 24 25 typedefs help clarify program. This declares an integer multiset that stores this program values in ascending order. ims; // multiset class-template definition // copy algorithm ims int. Multiset; // ims is typedef for "integer multiset" std: : ostream_iterator< int > output( cout, " " ); cout << "There are currently " << int. Multiset. count( 15 ) << " values of 15 in the multisetn" ; fig 21_19. cpp (1 of 3)
26 27 int. Multiset. insert( 15 ); 28 29 30 31 cout << "After inserts, there are " << int. Multiset. count( 15 ) << " values of 15 in the multisetnn" ; 32 33 34 // iterator that cannot be used to change element values Use member function ims: : const_iterator result; 35 36 37 // find 15 in int. Multiset; find returns iterator result = int. Multiset. find( 15 ); 38 39 40 41 42 43 // find 20 in int. Multiset; find returns iterator result = int. Multiset. find( 20 ); 44 45 46 if ( result == int. Multiset. end() ) // will be true hence cout << "Did not find value 20n" ; // did not find 20 47 48 49 // insert elements of array a into int. Multiset. insert( a, a + SIZE ); 50 51 52 cout << "n. After insert, int. Multiset contains: n"; std: : copy( int. Multiset. begin(), int. Multiset. end(), output ); 53 49 // insert 15 in int. Multiset if ( result != int. Multiset. end() ) // if iterator not at end cout << "Found value 15n"; // found search value 15 find. fig 21_19. cpp (2 of 3)
54 55 56 57 58 // determine lower and upper bound of 22 in int. Multiset cout << "nn. Lower bound of 22: " << *( int. Multiset. lower_bound( 22 ) ); cout << "n. Upper bound of 22: " << *( int. Multiset. upper_bound( 22 ) ); 59 60 61 // p represents pair of const_iterators std: : pair< ims: : const_iterator, ims: : const_iterator > p; 62 63 64 65 // use equal_range to determine lower and // of 22 in int. Multiset p = int. Multiset. equal_range( 22 ); Use a pair object to get the upperlower boundand upper bound for 22. 66 67 68 69 cout << "nnequal_range of 22: " << "n Lower bound: " << *( p. first ) << "n Upper bound: " << *( p. second ); 70 71 cout << endl; 72 73 return 0; 74 75 } // end main 50 fig 21_19. cpp (3 of 3)
51 There are currently 0 values of 15 in the multiset After inserts, there are 2 values of 15 in the multiset Found value 15 Did not find value 20 After insert, int. Multiset 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 fig 21_19. cpp output (1 of 1)
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;
53 1 2 3 // Fig. 21. 20: fig 21_20. cpp // Standard library class set test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <set> 9 10 11 // define short name for set type used in this program typedef std: : set< double, std: : less< double > > double_set; 12 13 #include <algorithm> 14 15 16 17 18 int main() { const int SIZE = 5; double a[ SIZE ] = { 2. 1, 4. 2, 9. 5, 2. 1, 3. 7 }; Create set. Syntax similar to multiset. 19 20 21 double_set double. Set( a, a + SIZE ); std: : ostream_iterator< double > output( cout, " " ); 22 23 24 cout << "double. Set contains: "; std: : copy( double. Set. begin(), double. Set. end(), output ); 25 fig 21_20. cpp (1 of 3)
26 27 // p represents pair containing const_iterator and bool std: : pair< double_set: : const_iterator, bool > p; 28 29 30 31 32 // insert 13. 8 in double. Set; insert returns pair in which // p. first represents location of 13. 8 in double. Set and // p. second represents whether 13. 8 was inserted pair object has a value representing p = double. Set. insert( 13. 8 ); // value not in set 33 34 35 cout << "nn" << *( p. first ) << ( p. second ? " was" : " was not" ) << " inserted"; 36 37 38 cout << "ndouble. Set contains: "; std: : copy( double. Set. begin(), double. Set. end(), output ); 39 40 41 // insert 9. 5 in double. Set p = double. Set. insert( 9. 5 ); 42 43 44 45 54 bool whether or not the item was inserted. // value already in set cout << "nn" << *( p. first ) << ( p. second ? " was" : " was not" ) << " inserted"; fig 21_20. cpp (2 of 3)
46 47 cout << "ndouble. Set contains: "; std: : copy( double. Set. begin(), double. Set. end(), output ); 48 49 cout << endl; 50 51 return 0; 52 53 55 } // end main double. Set contains: 2. 1 3. 7 4. 2 9. 5 13. 8 was inserted double. Set contains: 2. 1 3. 7 4. 2 9. 5 13. 8 9. 5 was not inserted double. Set contains: 2. 1 3. 7 4. 2 9. 5 13. 8 fig 21_20. cpp (3 of 3) fig 21_20. cpp output (1 of 1)
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
57 21. 3. 3 multimap Associative Container • Example std: : multimap< int, double, std: : less< int > > mmap. Object; – 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 mmap. Object; mmap. Object. insert( mmid: : value_type( 1, 3. 4 ) ); – Inserts key 1 with value 3. 4 – mmid: : value_type creates a pair object
58 1 2 3 // Fig. 21: fig 21_21. cpp // Standard library class multimap test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <map> 9 10 11 // define short name for multimap type used in this program typedef std: : multimap< int, double, std: : less< int > > mmid; 12 13 14 15 int main() { mmid pairs; 16 17 18 19 20 21 22 23 24 25 26 // map class-template definition Definition for a multimap that maps integer keys to double values. Create multimap and insert key-value pairs. cout << "There are currently " << pairs. count( 15 ) << " pairs with key 15 in the multimapn"; // insert two value_type objects in pairs. insert( mmid: : value_type( 15, 2. 7 ) ); pairs. insert( mmid: : value_type( 15, 99. 3 ) ); cout << "After inserts, there are " << pairs. count( 15 ) << " pairs with key 15nn" ; fig 21_21. cpp (1 of 2)
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 59 // insert five value_type objects in pairs. insert( mmid: : value_type( 30, 111. 11 ) ); pairs. insert( mmid: : value_type( 10, 22. 22 ) ); pairs. insert( mmid: : value_type( 25, 33. 333 ) ); pairs. insert( mmid: : value_type( 20, 9. 345 ) ); pairs. insert( mmid: : value_type( 5, 77. 54 ) ); Use iterator to cout << "Multimap pairs contains: n. Keyt. Valuen"; multimap. // use const_iterator to walk through elements of pairs for ( mmid: : const_iterator iter = pairs. begin(); iter != pairs. end(); ++iter ) cout << iter->first << 't' << iter->second << 'n'; 42 43 cout << endl; 44 45 return 0; 46 47 print entire } // end main fig 21_21. cpp (2 of 2)
60 There are currently 0 pairs with key 15 in the multimap After inserts, there are 2 pairs with key 15 Multimap pairs contains: Key Value 5 77. 54 10 22. 22 15 2. 7 15 99. 3 20 9. 345 25 33. 333 30 111. 11 fig 21_21. cpp output (1 of 1)
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 > >;
62 1 2 3 // Fig. 21. 22: fig 21_22. cpp // Standard library class map test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <map> 9 10 11 // define short name for map type used in this program typedef std: : map< int, double, std: : less< int > > mid; 12 13 14 15 int main() { mid pairs; 16 17 18 19 20 21 22 23 24 25 26 Again, use typedefs to simplify declaration. // map class-template definition // insert eight value_type objects in pairs. insert( mid: : value_type( 15, 2. 7 ) ); pairs. insert( mid: : value_type( 30, 111. 11 ) ); pairs. insert( mid: : value_type( 5, 1010. 1 ) ); pairs. insert( mid: : value_type( 10, 22. 22 ) ); pairs. insert( mid: : value_type( 25, 33. 333 ) ); pairs. insert( mid: : value_type( 5, 77. 54 ) ); // dupe ignored pairs. insert( mid: : value_type( 20, 9. 345 ) ); pairs. insert( mid: : value_type( 15, 99. 3 ) ); // dupe ignored fig 21_22. cpp (1 of 2) Duplicate keys ignored.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // use const_iterator to walk through elements of pairs for ( mid: : const_iterator iter = pairs. begin(); iter != pairs. end(); ++iter ) cout << iter->first << 't' Can use subscript << iter->second << 'n'; operator to add or change key-value pairs. // use subscript operator to change value for key 25 pairs[ 25 ] = 9999. 99; // use subscript operator insert value for key 40 pairs[ 40 ] = 8765. 43; cout << "n. After subscript operations, pairs contains: " << "n. Keyt. Valuen"; for ( mid: : const_iterator iter 2 = pairs. begin(); iter 2 != pairs. end(); ++iter 2 ) cout << iter 2 ->first << 't' << iter 2 ->second << 'n'; 48 49 cout << endl; 50 51 return 0; 52 53 63 cout << "pairs contains: n. Keyt. Valuen"; } // end main fig 21_22. cpp (2 of 2)
64 pairs contains: Key Value 5 1010. 1 10 22. 22 15 2. 7 20 9. 345 25 33. 333 30 111. 11 After subscript operations, pairs contains: Key Value 5 1010. 1 10 22. 22 15 2. 7 20 9. 345 25 9999. 99 30 111. 11 40 8765. 43 fig 21_22. cpp output (1 of 1)
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
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> > my. Stack; stack<type, list<type> > my. Other. Stack; stack<type> another. Stack; // default deque • vector, list – Implementation of stack (default deque) – Does not change behavior, just performance (deque and vector fastest)
1 2 3 // Fig. 21. 23: fig 21_23. cpp // Standard library adapter stack test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 #include <stack> #include <vector> #include <list> 11 12 13 14 // pop. Elements function-template prototype template< class T > void pop. Elements( T &stack. Ref ); 15 16 17 18 19 int main() { // stack with default underlying deque std: : stack< int > int. Deque. Stack; 67 // stack adapter definition // vector class-template definition // list class-template definition fig 21_23. cpp (1 of 3) Create stacks with various implementations. 20 21 22 // stack with underlying vector std: : stack< int, std: : vector< int > > int. Vector. Stack; 23 24 25 // stack with underlying list std: : stack< int, std: : list< int > > int. List. Stack; 26
68 27 28 29 30 31 // push the values 0 -9 onto each stack for ( int i = 0; i < 10; ++i ) { int. Deque. Stack. push( i ); int. Vector. Stack. push( i ); int. List. Stack. push( i ); 32 33 } // end for 34 35 36 37 38 39 40 41 // display and remove elements from each stack cout << "Popping from int. Deque. Stack: "; pop. Elements( int. Deque. Stack ); cout << "n. Popping from int. Vector. Stack: "; pop. Elements( int. Vector. Stack ); cout << "n. Popping from int. List. Stack: "; pop. Elements( int. List. Stack ); 42 43 cout << endl; 44 45 return 0; 46 47 48 } // end main Use member function push. fig 21_23. cpp (2 of 3)
49 50 51 52 53 54 55 56 57 58 59 69 // pop elements from stack object to which stack. Ref refers template< class T > void pop. Elements( T &stack. Ref ) { while ( !stack. Ref. empty() ) { cout << stack. Ref. top() << ' '; // view top element stack. Ref. pop(); // remove top element } // end while } // end function pop. Elements Popping from int. Deque. Stack: 9 8 7 6 5 4 3 2 1 0 Popping from int. Vector. Stack: 9 8 7 6 5 4 3 2 1 0 Popping from int. List. Stack: 9 8 7 6 5 4 3 2 1 0 fig 21_23. cpp (3 of 3) fig 21_23. cpp output (1 of 1)
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()
1 2 3 // Fig. 21. 24: fig 21_24. cpp // Standard library adapter queue test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <queue> 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // queue adapter definition int main() { std: : queue< double > values; // push elements values. push( 3. 2 values. push( 9. 8 values. push( 5. 4 Create queue, add values using push. fig 21_24. cpp (1 of 2) onto queue values ); ); ); cout << "Popping from values: "; while ( !values. empty() ) { cout << values. front() << ' '; values. pop(); } // end while 71 // view front element // remove element
27 cout << endl; 28 29 return 0; 30 31 72 } // end main Popping from values: 3. 2 9. 8 5. 4 fig 21_24. cpp (2 of 2) fig 21_24. cpp output (1 of 1)
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()
1 2 3 // Fig. 21. 25: fig 21_25. cpp // Standard library adapter priority_queue test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <queue> 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // priority_queue adapter definition Create priority queue. int main() { std: : priority_queue< double > priorities; // push elements priorities. push( onto priorities 3. 2 ); 9. 8 ); 5. 4 ); Insert items using push. When using pop, highest priority (largest) items removed first. cout << "Popping from priorities: " ; while ( !priorities. empty() ) { cout << priorities. top() << ' '; priorities. pop(); } // end while 74 // view top element // remove top element fig 21_25. cpp (1 of 2)
27 cout << endl; 28 29 return 0; 30 31 75 } // end main Popping from priorities: 9. 8 5. 4 3. 2 fig 21_25. cpp (2 of 2) fig 21_25. cpp output (1 of 1)
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>
77 21. 5. 1 fill, fill_n, generate and generate_n • Functions to change containers – fill(iterator 1, iterator 2, value); • Sets range of elements to value – fill_n(iterator 1, n, value); • Sets n elements to value, starting at iterator 1 – generate(iterator 1, iterator 2, function); • Like fill, but calls function to set each value – generate(iterator 1, quantity, function) • Like fill_n, ""
1 2 3 4 // Fig. 21. 26: fig 21_26. cpp // Standard library algorithms fill, fill_n, generate // and generate_n. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition 11 12 char next. Letter(); // prototype 13 14 15 16 17 Create vector of chars, to be used with various functions. int main() { std: : vector< char > chars( 10 ); std: : ostream_iterator< char > output( cout, " " ); 18 19 20 // fill chars with 5 s std: : fill( chars. begin(), chars. end(), '5' ); 21 22 23 cout << "Vector chars after filling with 5 s: n" ; std: : copy( chars. begin(), chars. end(), output ); 24 78 fig 21_26. cpp (1 of 3) Function fill.
25 26 // fill first five elements of chars with As std: : fill_n( chars. begin(), 5, 'A' ); 27 28 29 30 cout << "nn. Vector chars after filling five elements" << " with As: n"; std: : copy( chars. begin(), chars. end(), output ); 31 32 33 // generate values for all elements of chars with next. Letter std: : generate( chars. begin(), chars. end(), next. Letter ); 34 35 36 cout << "nn. Vector chars after generating letters A-J: n" ; std: : copy( chars. begin(), chars. end(), output ); 37 38 39 40 // generate values for first five elements of chars // with next. Letter std: : generate_n( chars. begin(), 5, next. Letter ); 41 42 43 44 cout << "nn. Vector chars after generating K-O for the" << " first five elements: n" ; std: : copy( chars. begin(), chars. end(), output ); 45 46 cout << endl; 47 48 return 0; 49 50 } // end main 79 Functions generate and generate_n use function next. Letter. fig 21_26. cpp (2 of 3)
80 51 52 53 54 55 56 // returns next letter in the alphabet (starts with A) char next. Letter() { static char letter = 'A'; return letter++; 57 58 } // end function next. Letter Vector chars after filling with 5 s: 55555 Vector chars after filling five elements with As: AAAAA 55555 Vector chars after generating letters A-J: ABCDEFGHIJ Vector chars after generating K-O for the first five elements: KLMNOFGHIJ fig 21_26. cpp (3 of 3) fig 21_26. cpp output (1 of 1)
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(iterator 1, iterator 2, iterator 3); • Compares sequence from iterator 1 to iterator 2 with sequence beginning at iterator 3 – 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 > my. Pair. Object; my. Pair. Object = mismatch( iter 1, iter 2, iter 3); 81
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(iter 1, iter 2, iter 3); 82
1 2 3 4 // Fig. 21. 27: fig 21_27. cpp // Standard library functions equal, // mismatch and lexicographical_compare. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> 11 12 13 14 15 16 int main() { const int SIZE = 10; int a 1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int a 2[ SIZE ] = { 1, 2, 3, 4, 1000, 6, 7, 8, 9, 10 }; // algorithm definitions // vector class-template definition 17 18 19 20 std: : vector< int > v 1( a 1, a 1 + SIZE ); std: : vector< int > v 2( a 1, a 1 + SIZE ); std: : vector< int > v 3( a 2, a 2 + SIZE ); 21 22 std: : ostream_iterator< int > output( cout, " " ); 23 83 fig 21_27. cpp (1 of 3)
84 24 25 26 27 28 29 cout << "Vector v 1 contains: "; std: : copy( v 1. begin(), v 1. end(), output ); cout << "n. Vector v 2 contains: "; std: : copy( v 2. begin(), v 2. end(), output ); cout << "n. Vector v 3 contains: "; std: : copy( v 3. begin(), v 3. end(), output ); 30 31 32 33 // compare vectors v 1 and v 2 for equality bool result = std: : equal( v 1. begin(), v 1. end(), v 2. begin() ); 34 35 36 cout << "nn. Vector v 1 " << ( result ? "is" : "is not" ) << " equal to vector v 2. n" ; 37 38 39 40 41 // compare vectors v 1 and v 3 for equality result = std: : equal( v 1. begin(), v 1. end(), v 3. begin() ); cout << "Vector v 1 " << ( result ? "is" : "is not" ) << " equal to vector v 3. n" ; 42 43 44 45 // location represents pair of vector iterators std: : pair< std: : vector< int >: : iterator, std: : vector< int >: : iterator > location; 46 47 48 49 // check for mismatch between v 1 and v 3 location = std: : mismatch( v 1. begin(), v 1. end(), v 3. begin() ); 50 Use function equal. Compares all of v 1 with v 2. fig 21_27. cpp (2 of 3) Note use of function mismatch.
51 52 53 54 55 cout << << << 56 57 58 char c 1[ SIZE ] = "HELLO"; char c 2[ SIZE ] = "BYE BYE"; 59 60 61 62 // perform lexicographical comparison of c 1 and c 2 result = std: : lexicographical_compare( c 1, c 1 + SIZE, c 2 + SIZE ); 63 64 65 66 67 cout << c 1 << ( result ? " is less than " : " is greater than or equal to " ) << c 2 << endl; 68 69 return 0; 70 71 85 "n. There is a mismatch between v 1 and v 3 at " "location " << ( location. first - v 1. begin() ) "nwhere v 1 contains " << *location. first " and v 3 contains " << *location. second "nn"; } // end main Use lexicographical_compare. fig 21_27. cpp (3 of 3)
86 Vector v 1 contains: 1 2 3 4 5 6 7 8 9 10 Vector v 2 contains: 1 2 3 4 5 6 7 8 9 10 Vector v 3 contains: 1 2 3 4 1000 6 7 8 9 10 Vector v 1 is equal to vector v 2. Vector v 1 is not equal to vector v 3. There is a mismatch between v 1 and v 3 at location 4 where v 1 contains 5 and v 3 contains 1000 HELLO is greater than or equal to BYE fig 21_27. cpp output (1 of 1)
21. 5. 3 remove, remove_if, remove_copy and remove_copy_if • remove – remove( iter 1, iter 2, value); – Removes all instances of value in range (iter 1 -iter 2) • 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(iter 1, iter 2, iter 3, value); • Copies elements not equal to value into iter 3 (output iterator) • Uses range iter 1 -iter 2 87
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(iter 1, iter 2, function); • Elements passed to function, which returns a bool • remove_copy_if – Like remove_copy and remove_if – Copies range of elements to iter 3, except those for which function returns true remove_copy_if(iter 1, iter 2, iter 3, function); 88
89 1 2 3 4 // Fig. 21. 28: fig 21_28. cpp // Standard library functions remove, remove_if, // remove_copy and remove_copy_if. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition 11 12 bool greater 9( int ); // prototype 13 14 15 16 17 18 19 20 21 22 23 24 25 26 int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; std: : ostream_iterator< int > output( cout, " " ); std: : vector< int > v( a, a + SIZE ); std: : vector< int >: : iterator new. Last. Element; cout << "Vector v before removing all 10 s: n std: : copy( v. begin(), v. end(), output ); "; fig 21_28. cpp (1 of 4)
90 27 28 // remove 10 from v new. Last. Element = std: : remove( v. begin(), v. end(), 10 ); 29 30 31 cout << "n. Vector v after removing all 10 s: n "; std: : copy( v. begin(), new. Last. Element, output ); 32 33 34 std: : vector< int > v 2( a, a + SIZE ); std: : vector< int > c( SIZE, 0 ); 35 36 37 38 cout << "nn. Vector v 2 before removing all 10 s " << "and copying: n "; std: : copy( v 2. begin(), v 2. end(), output ); 39 40 41 // copy from v 2 to c, removing 10 s in the process std: : remove_copy( v 2. begin(), v 2. end(), c. begin(), 10 ); 42 43 44 cout << "n. Vector c after removing all 10 s from v 2: n std: : copy( c. begin(), c. end(), output ); 45 46 std: : vector< int > v 3( a, a + SIZE ); 47 48 49 50 cout << "nn. Vector v 3 before removing all elements" << "ngreater than 9: n "; std: : copy( v 3. begin(), v 3. end(), output ); 51 Remove all 10's from v. Returns an iterator pointing to the new last element. "; Use remove_copy to create a duplicate of v, with all the fig 21_28. cpp 10's removed. (2 of 4)
52 53 54 // remove elements greater than 9 from v 3 new. Last. Element = std: : remove_if( v 3. begin(), v 3. end(), greater 9 ); 55 56 57 58 cout << "n. Vector v 3 after removing all elements" << "ngreater than 9: n "; std: : copy( v 3. begin(), new. Last. Element, output ); 59 60 61 std: : vector< int > v 4( a, a + SIZE ); std: : vector< int > c 2( SIZE, 0 ); 62 63 64 65 66 67 68 69 70 71 72 73 74 75 91 Use function greater 9 to determine whether to remove the element. cout << "nn. Vector v 4 before removing all elements" << "ngreater than 9 and copying: n "; std: : copy( v 4. begin(), v 4. end(), output ); Note use of remove_copy_if. // copy elements from v 4 to c 2, removing elements greater // than 9 in the process std: : remove_copy_if( v 4. begin(), v 4. end(), c 2. begin(), greater 9 ); cout << "n. Vector c 2 after removing all elements" << "ngreater than 9 from v 4: n "; std: : copy( c 2. begin(), c 2. end(), output ); fig 21_28. cpp (3 of 4)
76 cout << endl; 77 78 return 0; 79 80 } // end main 81 82 83 84 85 // determine whether argument is greater than 9 bool greater 9( int x ) { return x > 9; 86 87 } // end greater 9 92 fig 21_28. cpp (4 of 4)
93 Vector v before removing all 10 s: 10 2 10 4 16 6 14 8 12 10 Vector v after removing all 10 s: 2 4 16 6 14 8 12 Vector v 2 before removing all 10 s and copying: 10 2 10 4 16 6 14 8 12 10 Vector c after removing all 10 s from v 2: 2 4 16 6 14 8 12 0 0 0 Vector v 3 before removing all elements greater than 9: 10 2 10 4 16 6 14 8 12 10 Vector v 3 after removing all elements greater than 9: 2 4 6 8 Vector v 4 before removing all elements greater than 9 and copying: 10 2 10 4 16 6 14 8 12 10 Vector c 2 after removing all elements greater than 9 from v 4: 2 4 6 8 0 0 0 fig 21_28. cpp output (1 of 1)
21. 5. 4 replace, replace_if, replace_copy and replace_copy_if • Functions – replace( iter 1, iter 2, value, newvalue ); • Like remove, except replaces value with newvalue – replace_if( iter 1, iter 2, function, newvalue ); • Replaces value if function returns true – replace_copy(iter 1, iter 2, iter 3, value, newvalue); • Replaces and copies elements to iter 3 • Does not affect originals – replace_copy_if( iter 1, iter 2, iter 3, function, newvalue ); • Replaces and copies elements to iter 3 if function returns true 94
1 2 3 4 // Fig. 21. 29: fig 21_29. cpp // Standard library functions replace, replace_if, // replace_copy and replace_copy_if. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> 11 12 bool greater 9( int ); 13 14 15 16 17 95 int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; 18 19 std: : ostream_iterator< int > output( cout, " " ); 20 21 22 23 std: : vector< int > v 1( a, a + SIZE ); cout << "Vector v 1 before replacing all 10 s: n std: : copy( v 1. begin(), v 1. end(), output ); 24 "; fig 21_29. cpp (1 of 4)
25 26 // replace 10 s in v 1 with 100 std: : replace( v 1. begin(), v 1. end(), 100 ); 27 28 29 cout << "n. Vector v 1 after replacing 10 s with 100 s: n std: : copy( v 1. begin(), v 1. end(), output ); 30 31 32 std: : vector< int > v 2( a, a + SIZE ); std: : vector< int > c 1( SIZE ); 33 34 35 36 cout << "nn. Vector v 2 before replacing all 10 s " << "and copying: n "; std: : copy( v 2. begin(), v 2. end(), output ); 37 38 39 40 // copy from v 2 to c 1, replacing 10 s with 100 s std: : replace_copy( v 2. begin(), v 2. end(), c 1. begin(), 100 ); 41 42 43 cout << "n. Vector c 1 after replacing all 10 s in v 2: n std: : copy( c 1. begin(), c 1. end(), output ); 44 45 std: : vector< int > v 3( a, a + SIZE ); 46 47 48 49 cout << "nn. Vector v 3 before replacing values greater" << " than 9: n "; std: : copy( v 3. begin(), v 3. end(), output ); 50 96 Use functions replace, replace_copy. "; fig 21_29. cpp (2 of 4) ";
51 52 // replace values greater than 9 in v 3 with 100 std: : replace_if( v 3. begin(), v 3. end(), greater 9, 100 ); 53 54 55 56 cout << "n. Vector v 3 after replacing all values greater" << "nthan 9 with 100 s: n "; std: : copy( v 3. begin(), v 3. end(), output ); 57 58 59 std: : vector< int > v 4( a, a + SIZE ); std: : vector< int > c 2( SIZE ); 60 61 62 63 cout << "nn. Vector v 4 before replacing all values greater " << "than 9 and copying: n "; std: : copy( v 4. begin(), v 4. end(), output ); 64 65 66 67 // copy v 4 to c 2, replacing elements greater than 9 with 100 std: : replace_copy_if( v 4. begin(), v 4. end(), c 2. begin(), greater 9, 100 ); 68 69 70 71 cout << "n. Vector c 2 after replacing all values greater " << "than 9 in v 4: n "; std: : copy( c 2. begin(), c 2. end(), output ); 72 73 cout << endl; 74 75 return 0; 76 77 } // end main 97 fig 21_29. cpp (3 of 4)
98 78 79 80 81 82 // determine whether argument is greater than 9 bool greater 9( int x ) { return x > 9; 83 84 } // end function greater 9 Vector v 1 before replacing all 10 s: 10 2 10 4 16 6 14 8 12 10 Vector v 1 after replacing 10 s with 100 s: 100 2 100 4 16 6 14 8 12 100 Vector v 2 before replacing all 10 s and copying: 10 2 10 4 16 6 14 8 12 10 Vector c 1 after replacing all 10 s in v 2: 100 2 100 4 16 6 14 8 12 100 Vector v 3 before replacing values greater than 9: 10 2 10 4 16 6 14 8 12 10 Vector v 3 after replacing all values greater fig 21_29. cpp (4 of 4) fig 21_29. cpp output (1 of 1)
99 21. 5. 5 Mathematical Algorithms • random_shuffle(iter 1, iter 2) – Randomly mixes elements in range • count(iter 1, iter 2, value) – Returns number of instances of value in range • count_if(iter 1, iter 2, function) – Counts number of instances that return true • min_element(iter 1, iter 2) – Returns iterator to smallest element • max_element(iter 1, iter 2) – Returns iterator to largest element
100 21. 5. 5 Mathematical Algorithms • accumulate(iter 1, iter 2) – Returns sum of elements in range • for_each(iter 1, iter 2, function) – Calls function on every element in range – Does not modify element • transform(iter 1, iter 2, iter 3, function) – Calls function for all elements in range of iter 1 -iter 2, copies result to iter 3
1 2 3 // Fig. 21. 30: fig 21_30. cpp // Mathematical algorithms of the standard library. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 #include <algorithm> #include <numeric> #include <vector> 11 12 13 14 bool greater 9( int ); void output. Square( int ); int calculate. Cube( int ); 15 16 17 18 19 int main() { const int SIZE = 10; int a 1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // algorithm definitions // accumulate is defined here 20 21 22 std: : vector< int > v( a 1, a 1 + SIZE ); std: : ostream_iterator< int > output( cout, " " ); 23 24 25 cout << "Vector v before random_shuffle: " ; std: : copy( v. begin(), v. end(), output ); 26 101 fig 21_30. cpp (1 of 5)
27 28 // shuffle elements of v std: : random_shuffle( v. begin(), v. end() ); 29 30 31 cout << "n. Vector v after random_shuffle: " ; std: : copy( v. begin(), v. end(), output ); 32 33 34 35 36 37 38 39 40 int a 2[] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 }; std: : vector< int > v 2( a 2, a 2 + SIZE ); cout << "nn. Vector v 2 contains: "; std: : copy( v 2. begin(), v 2. end(), output ); // count number of elements in v 2 with value 8 int result = std: : count( v 2. begin(), v 2. end(), 8 ); 41 42 43 44 45 // count number of elements in v 2 that are greater than 9 result = std: : count_if( v 2. begin(), v 2. end(), greater 9 ); 46 47 cout << "n. Number of elements greater than 9: " << result; 48 102 std: : cout << "n. Number of elements matching 8: " << result; fig 21_30. cpp (2 of 5)
49 50 51 // locate minimum element in v 2 cout << "nn. Minimum element in Vector v 2 is: " << *( std: : min_element( v 2. begin(), v 2. end() ) ); 52 53 54 55 // locate maximum element in v 2 cout << "n. Maximum element in Vector v 2 is: " << *( std: : max_element( v 2. begin(), v 2. end() ) ); 56 57 58 59 // calculate sum of elements in v cout << "nn. The total of the elements in Vector v is: " << std: : accumulate( v. begin(), v. end(), 0 ); 60 61 cout << "nn. The square of every integer in Vector v is: n" ; 62 63 64 // output square of every element in v std: : for_each( v. begin(), v. end(), output. Square ); 65 66 67 68 69 70 71 std: : vector< int > cubes( SIZE ); // calculate cube of each element in v; // place results in cubes std: : transform( v. begin(), v. end(), cubes. begin(), calculate. Cube ); 103 fig 21_30. cpp (3 of 5)
104 72 73 74 cout << "nn. The cube of every integer in Vector v is: n" ; std: : copy( cubes. begin(), cubes. end(), output ); 75 76 cout << endl; 77 78 return 0; 79 80 } // end main 81 82 83 84 85 // determine whether argument is greater than 9 bool greater 9( int value ) { return value > 9; 86 87 } // end function greater 9 88 89 90 91 92 // output square of argument void output. Square( int value ) { cout << value * value << ' '; 93 94 } // end function output. Square 95 fig 21_30. cpp (4 of 5)
96 97 98 99 105 // return cube of argument int calculate. Cube( int value ) { return value * value; 100 101 } // end function calculate. Cube Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10 Vector v after random_shuffle: 5 4 1 3 7 8 9 10 6 2 Vector v 2 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 v 2 is: 1 Maximum element in Vector v 2 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 fig 21_30. cpp (5 of 5) fig 21_30. cpp output (1 of 1)
21. 5. 6 Basic Searching and Sorting Algorithms • find(iter 1, iter 2, value) – Returns iterator to first instance of value (in range) • find_if(iter 1, iter 2, function) – Like find – Returns iterator when function returns true • sort(iter 1, iter 2) – Sorts elements in ascending order • binary_search(iter 1, iter 2, value) – Searches ascending sorted list for value – Uses binary search 106
1 2 3 // Fig. 21. 31: fig 21_31. cpp // Standard library search and sort algorithms. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <algorithm> #include <vector> 10 11 bool greater 10( int value ); 12 13 14 15 16 int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 17 18 19 20 21 22 23 24 25 26 107 // algorithm definitions // vector class-template definition // prototype std: : vector< int > v( a, a + SIZE ); std: : ostream_iterator< int > output( cout, " " ); cout << "Vector v contains: "; std: : copy( v. begin(), v. end(), output ); // locate first occurrence of 16 in v std: : vector< int >: : iterator location; location = std: : find( v. begin(), v. end(), 16 ); fig 21_31. cpp (1 of 4)
108 27 28 29 30 31 32 33 34 35 // locate first occurrence of 100 in v location = std: : find( v. begin(), v. end(), 100 ); 36 37 38 39 40 41 if ( location != v. end() ) cout << "n. Found 100 at location " << ( location - v. begin() ); else cout << "n 100 not found"; 42 43 44 // locate first occurrence of value greater than 10 in v location = std: : find_if( v. begin(), v. end(), greater 10 ); 45 46 47 48 49 50 51 if ( location != v. end() ) cout << "nn. The first value greater than 10 is " << *location << "nfound at location " << ( location - v. begin() ); else cout << "nn. No values greater than 10 were found" ; 52 if ( location != v. end() ) cout << "nn. Found 16 at location " << ( location - v. begin() ); else cout << "nn 16 not found"; fig 21_31. cpp (2 of 4)
53 54 // sort elements of v std: : sort( v. begin(), v. end() ); 55 56 57 cout << "nn. Vector v after sort: "; std: : copy( v. begin(), v. end(), output ); 58 59 60 61 62 63 // use binary_search to locate 13 in v if ( std: : binary_search( v. begin(), v. end(), 13 ) ) cout << "nn 13 was found in v"; else cout << "nn 13 was not found in v" ; 64 65 66 67 68 69 // use binary_search to locate 100 in v if ( std: : binary_search( v. begin(), v. end(), 100 ) ) cout << "n 100 was found in v"; else cout << "n 100 was not found in v" ; 70 71 cout << endl; 72 73 return 0; 74 75 76 } // end main 109 fig 21_31. cpp (3 of 4)
77 78 79 80 // determine whether argument is greater than 10 bool greater 10( int value ) { return value > 10; 81 82 } // end function greater 10 110 Vector v contains: 10 2 17 5 16 8 13 11 20 7 Found 16 at location 4 100 not found The first value greater than 10 is 17 found at location 2 Vector v after sort: 2 5 7 8 10 11 13 16 17 20 13 was found in v 100 was not found in v fig 21_31. cpp (4 of 4) fig 21_31. cpp output (1 of 1)
111 21. 5. 7 swap, iter_swap and swap_ranges • swap(element 1, element 2) – Exchanges two values – swap( a[ 0 ], a[ 1 ] ); • iter_swap(iter 1, iter 2) – Exchanges the values to which the iterators refer • swap_ranges(iter 1, iter 2, iter 3) – Swap the elements from iter 1 -iter 2 with elements beginning at iter 3
1 2 3 // Fig. 21. 32: fig 21_32. cpp // Standard library algorithms iter_swap, swap and swap_ranges. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <algorithm> 9 10 11 12 13 14 int main() { const int SIZE = 10; int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std: : ostream_iterator< int > output( cout, " " ); // algorithm definitions 15 16 17 cout << "Array a contains: n "; std: : copy( a, a + SIZE, output ); 18 19 20 // swap elements at locations 0 and 1 of array a std: : swap( a[ 0 ], a[ 1 ] ); 21 22 23 24 cout << "n. Array a after swapping a[0] and a[1] " << "using swap: n "; std: : copy( a, a + SIZE, output ); 25 112 fig 21_32. cpp (1 of 2)
26 27 28 29 30 31 // use iterators to swap elements at locations // 0 and 1 of array a std: : iter_swap( &a[ 0 ], &a[ 1 ] ); cout << "n. Array a after swapping a[0] and a[1] " << "using iter_swap: n "; std: : copy( a, a + SIZE, output ); 32 33 34 35 // swap elements in first five elements of array a with // elements in last five elements of array a std: : swap_ranges( a, a + 5 ); 36 37 38 39 cout << "n. Array a after swapping the first five elementsn" << "with the last five elements: n "; std: : copy( a, a + SIZE, output ); 40 41 cout << endl; 42 43 return 0; 44 45 } // end main 113 fig 21_32. cpp (2 of 2)
114 Array a contains: 1 2 3 4 5 6 7 8 9 10 Array a after swapping a[0] and a[1] using swap: 2 1 3 4 5 6 7 8 9 10 Array a after swapping a[0] and a[1] using iter_swap: 1 2 3 4 5 6 7 8 9 10 Array a after swapping the first five elements with the last five elements: 6 7 8 9 10 1 2 3 4 5 fig 21_32. cpp output (1 of 1)
21. 5. 8 copy_backward, merge, unique and reverse • copy_backward(iter 1, iter 2, iter 3) – Copy elements from iter 1 -iter 2 to iter 3, in reverse order • merge(iter 1, iter 2, iter 3, iter 4, iter 5) – Ranges iter 1 -iter 2 and iter 3 -iter 4 must be sorted in ascending order – merge copies both lists into iter 5, in ascending order • unique(iter 1, iter 2) – Removes duplicate elements from a sorted list – Returns iterator to new end of sequence • reverse(iter 1, iter 2) – Reverses elements from iter 1 -iter 2 115
1 2 3 4 // Fig. 21. 33: fig 21_33. cpp // Standard library functions copy_backward, merge, // unique and reverse. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> 11 12 13 14 15 16 17 18 19 116 // algorithm definitions // vector class-template definition int main() { const int SIZE = 5; int a 1[ SIZE ] = { 1, 3, 5, 7, 9 }; int a 2[ SIZE ] = { 2, 4, 5, 7, 9 }; std: : vector< int > v 1( a 1, a 1 + SIZE ); std: : vector< int > v 2( a 2, a 2 + SIZE ); 20 21 std: : ostream_iterator< int > output( cout, " " ); 22 23 24 25 26 cout << "Vector v 1 contains: "; std: : copy( v 1. begin(), v 1. end(), output ); cout << "n. Vector v 2 contains: "; std: : copy( v 2. begin(), v 2. end(), output ); fig 21_33. cpp (1 of 3)
117 27 28 std: : vector< int > results( v 1. size() ); 29 30 31 // place elements of v 1 into results in reverse order std: : copy_backward( v 1. begin(), v 1. end(), results. end() ); 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 cout << "nn. After copy_backward, results contains: " ; std: : copy( results. begin(), results. end(), output ); std: : vector< int > results 2( v 1. size() + v 2. size() ); // merge elements of v 1 and v 2 into results 2 in sorted order std: : merge( v 1. begin(), v 1. end(), v 2. begin(), v 2. end(), results 2. begin() ); cout << "nn. After merge of v 1 and v 2 results 2 contains: n" ; std: : copy( results 2. begin(), results 2. end(), output ); // eliminate duplicate values from results 2 std: : vector< int >: : iterator end. Location; end. Location = std: : unique( results 2. begin(), results 2. end() ); cout << "nn. After unique results 2 contains: n" ; std: : copy( results 2. begin(), end. Location, output ); fig 21_33. cpp (2 of 3)
53 54 55 56 // reverse elements of v 1 std: : reverse( v 1. begin(), v 1. end() ); 57 58 std: : copy( v 1. begin(), v 1. end(), output ); 59 60 cout << endl; 61 62 return 0; 63 64 118 cout << "nn. Vector v 1 after reverse: "; } // end main Vector v 1 contains: 1 3 5 7 9 Vector v 2 contains: 2 4 5 7 9 After copy_backward, results contains: 1 3 5 7 9 After merge of v 1 and v 2 results 2 contains: 1234557799 After unique results 2 contains: 1234579 fig 21_33. cpp (3 of 3) fig 21_33. cpp output (1 of 1)
21. 5. 9 inplace_merge, unique_copy and reverse_copy • inplace_merge(iter 1, iter 2, iter 3) – Merges two sorted sequences (iter 1 -iter 2, iter 2 -iter 3) inside the same container • unique_copy(iter 1, iter 2, iter 3) – Copies all unique elements in sorted array (from iter 1 -iter 2) into iter 3 • reverse_copy(iter 1, iter 2, iter 3) – Reverses elements in iter 1 -iter 2, copies into iter 3 119
1 2 3 4 // Fig. 21. 34: fig 21_34. cpp // Standard library algorithms inplace_merge, // reverse_copy and unique_copy. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 11 #include <algorithm> #include <vector> #include <iterator> 12 13 14 15 16 17 int main() { const int SIZE = 10; int a 1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 }; std: : vector< int > v 1( a 1, a 1 + SIZE ); // algorithm definitions // vector class-template definition // back_inserter definition 18 19 std: : ostream_iterator< int > output( cout, " " ); 20 21 22 cout << "Vector v 1 contains: "; std: : copy( v 1. begin(), v 1. end(), output ); 23 24 25 26 // merge first half of v 1 with second half of v 1 such that // v 1 contains sorted set of elements after merge std: : inplace_merge( v 1. begin(), v 1. begin() + 5, v 1. end() ); 27 120 fig 21_34. cpp (1 of 2)
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 std: : vector< int > results 1; // copy only unique elements of v 1 into results 1 std: : unique_copy( v 1. begin(), v 1. end(), std: : back_inserter( results 1 ) ); cout << "n. After unique_copy results 1 contains: " ; std: : copy( results 1. begin(), results 1. end(), output ); std: : vector< int > results 2; cout << "n. After reverse_copy, results 2 contains: " ; // copy elements of v 1 into results 2 in reverse order std: : reverse_copy( v 1. begin(), v 1. end(), std: : back_inserter( results 2 ) ); 47 48 std: : copy( results 2. begin(), results 2. end(), output ); 49 50 cout << endl; 51 52 return 0; 53 54 121 cout << "n. After inplace_merge, v 1 contains: "; std: : copy( v 1. begin(), v 1. end(), output ); } // end main fig 21_34. cpp (2 of 2)
122 Vector v 1 contains: 1 3 5 7 9 After inplace_merge, v 1 contains: 1 1 3 3 5 5 7 7 9 9 After unique_copy results 1 contains: 1 3 5 7 9 After reverse_copy, results 2 contains: 9 9 7 7 5 5 3 3 1 1 fig 21_34. cpp output (1 of 1)
123 21. 5. 10 Set Operations • includes(iter 1, iter 2, iter 3, iter 4) – Returns true if iter 1 -iter 2 contains iter 3 -iter 4 – Both ranges must be sorted a 1: 1 2 3 4 a 2: 1 3 a 1 includes a 3 • set_difference(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in first set (1 -2) that are not in second set (3 -4) into iter 5 • set_intersection(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies common elements from the two sets (1 -2, 3 -4) into iter 5
124 21. 5. 10 Set Operations • set_symmetric_difference(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in set (1 -2) but not set (3 -4), and vice versa, into iter 5 • a 1: 1 2 3 4 5 6 7 8 9 10 • a 2: 4 5 6 7 8 • set_symmetric_difference: 1 2 3 9 10 – Both sets must be sorted • set_union( iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in either or both sets to iter 5 – Both sets must be sorted
1 2 3 4 // Fig. 21. 35: fig 21_35. cpp // Standard library algorithms includes, set_difference, // set_intersection, set_symmetric_difference and set_union. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 #include <algorithm> 10 11 12 13 14 15 16 17 int main() { const int SIZE 1 = 10, SIZE 2 = 5, SIZE 3 = 20; int a 1[ SIZE 1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int a 2[ SIZE 2 ] = { 4, 5, 6, 7, 8 }; int a 3[ SIZE 2 ] = { 4, 5, 6, 11, 15 }; std: : ostream_iterator< int > output( cout, " " ); 18 19 20 21 22 23 24 25 125 // algorithm definitions cout << "a 1 contains: "; std: : copy( a 1, a 1 + SIZE 1, output ); cout << "na 2 contains: "; std: : copy( a 2, a 2 + SIZE 2, output ); cout << "na 3 contains: "; std: : copy( a 3, a 3 + SIZE 2, output ); fig 21_35. cpp (1 of 3)
26 27 28 29 30 31 32 33 34 35 36 // determine whether set a 3 is completely contained in a 1 if ( std: : includes( a 1, a 1 + SIZE 1, a 3 + SIZE 2 ) ) cout << "na 1 includes a 3"; else cout << "na 1 does not include a 3" ; 37 38 int difference[ SIZE 1 ]; 39 40 41 42 // determine elements of a 1 not in a 2 int *ptr = std: : set_difference( a 1, a 1 + SIZE 1, a 2 + SIZE 2, difference ); 43 44 45 cout << "nnset_difference of a 1 and a 2 is: "; std: : copy( difference, ptr, output ); 46 47 intersection[ SIZE 1 ]; 48 49 50 51 // determine elements in both a 1 and a 2 ptr = std: : set_intersection( a 1, a 1 + SIZE 1, a 2 + SIZE 2, intersection ); 52 126 // determine whether set a 2 is completely contained in a 1 if ( std: : includes( a 1, a 1 + SIZE 1, a 2 + SIZE 2 ) ) cout << "nna 1 includes a 2"; else cout << "nna 1 does not include a 2" ; fig 21_35. cpp (2 of 3)
53 54 55 56 57 58 59 60 61 62 63 64 int symmetric_difference[ SIZE 1 ]; // determine elements of a 1 that are not in a 2 and // elements of a 2 that are not in a 1 ptr = std: : set_symmetric_difference( a 1, a 1 + SIZE 1, a 2 + SIZE 2, symmetric_difference ); cout << "nnset_symmetric_difference of a 1 and a 2 is: "; std: : copy( symmetric_difference, ptr, output ); 65 66 int union. Set[ SIZE 3 ]; 67 68 69 70 // determine elements that are in either or both sets ptr = std: : set_union( a 1, a 1 + SIZE 1, a 3 + SIZE 2, union. Set ); 71 72 73 74 75 76 77 78 79 127 cout << "nnset_intersection of a 1 and a 2 is: "; std: : copy( intersection, ptr, output ); cout << "nnset_union of a 1 and a 3 is: "; std: : copy( union. Set, ptr, output ); cout << endl; return 0; } // end main fig 21_35. cpp (3 of 3)
128 a 1 contains: 1 2 3 4 5 6 7 8 9 10 a 2 contains: 4 5 6 7 8 a 3 contains: 4 5 6 11 15 a 1 includes a 2 a 1 does not include a 3 set_difference of a 1 and a 2 is: 1 2 3 9 10 set_intersection of a 1 and a 2 is: 4 5 6 7 8 set_symmetric_difference of a 1 and a 2 is: 1 2 3 9 10 set_union of a 1 and a 3 is: 1 2 3 4 5 6 7 8 9 10 11 15 fig 21_35. cpp output (1 of 1)
21. 5. 11 lower_bound, upper_bound and equal_range • lower_bound(iter 1, iter 2, value) – For sorted elements, returns iterator to the first location where value could be inserted and elements remain sorted • upper_bound(iter 1, iter 2, value) – Same as lower_bound, but returns iterator to last element where value could be inserted • equal_range(iter 1, iter 2, value) – Returns two iterators, a lower_bound an upper_bound – Assign them to a pair object 129
1 2 3 4 // Fig. 21. 36: fig 21_36. cpp // Standard library functions lower_bound, upper_bound and // equal_range for a sorted sequence of values. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> 11 12 13 14 15 16 17 int main() { const int SIZE = 10; int a 1[] = { 2, 2, 4, 4, 4, 6, 6, 8 }; std: : vector< int > v( a 1, a 1 + SIZE ); std: : ostream_iterator< int > output( cout, " " ); 18 19 20 21 22 23 24 25 130 // algorithm definitions // vector class-template definition cout << "Vector v contains: n"; std: : copy( v. begin(), v. end(), output ); // determine lower-bound insertion point for 6 in v std: : vector< int >: : iterator lower; lower = std: : lower_bound( v. begin(), v. end(), 6 ); fig 21_36. cpp (1 of 4)
26 27 28 29 30 31 32 33 34 // determine upper-bound insertion point for 6 in v std: : vector< int >: : iterator upper; upper = std: : upper_bound( v. begin(), v. end(), 6 ); cout << "n. Upper bound of 6 is element " << ( upper - v. begin() ) << " of vector v"; 35 36 37 38 39 40 // use equal_range to determine both the lower- and // upper-bound insertion points for 6 std: : pair< std: : vector< int >: : iterator, std: : vector< int >: : iterator > eq; eq = std: : equal_range( v. begin(), v. end(), 6 ); 41 42 43 44 45 46 cout << << << cout << << 47 48 49 cout << "nn. Use lower_bound to locate the first pointn" << "at which 5 can be inserted in order" ; 50 131 cout << "nn. Lower bound of 6 is element " << ( lower - v. begin() ) << " of vector v"; "n. Using equal_range: n" " Lower bound of 6 is element " ( eq. first - v. begin() ) << " of vector v"; "n Upper bound of 6 is element " ( eq. second - v. begin() ) << " of vector v"; fig 21_36. cpp (2 of 4)
51 52 // determine lower-bound insertion point for 5 in v lower = std: : lower_bound( v. begin(), v. end(), 5 ); 53 54 55 cout << "n Lower bound of 5 is element " << ( lower - v. begin() ) << " of vector v"; 56 57 58 cout << "nn. Use upper_bound to locate the last pointn" << "at which 7 can be inserted in order" ; 59 60 61 // determine upper-bound insertion point for 7 in v upper = std: : upper_bound( v. begin(), v. end(), 7 ); 62 63 64 cout << "n Upper bound of 7 is element " << ( upper - v. begin() ) << " of vector v"; 65 66 67 cout << "nn. Use equal_range to locate the first andn" << "last point at which 5 can be inserted in order" ; 68 69 70 71 // use equal_range to determine both the lower- and // upper-bound insertion points for 5 eq = std: : equal_range( v. begin(), v. end(), 5 ); 72 73 74 75 76 77 cout << << << "n Lower bound of 5 is element " ( eq. first - v. begin() ) << " of vector v"; "n Upper bound of 5 is element " ( eq. second - v. begin() ) << " of vector v" endl; 132 fig 21_36. cpp (3 of 4)
78 79 80 81 133 return 0; } // end main Vector v contains: 2244466668 Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Using equal_range: Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Use lower_bound to locate the first point at which 5 can be inserted in order Lower bound of 5 is element 5 of vector v Use upper_bound to locate the last point at which 7 can be inserted in order fig 21_36. cpp (4 of 4) fig 21_36. cpp output (1 of 1)
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(iter 1, iter 2) • Creates a heap in the range of the iterators • Must be random access iterators (arrays, vectors, deques) – sort_heap(iter 1, iter 2) • Sorts a heap sequence from iter 1 to iter 2
135 21. 5. 12 Heapsort • Functions – push_heap(iter 1, iter 2) • The iterators must specify a heap • Adds last element in object to heap – Assumes other elements already in heap order – pop_heap(iter 1, iter 2) • 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
1 2 3 4 // Fig. 21. 37: fig 21_37. cpp // Standard library algorithms push_heap, pop_heap, // make_heap and sort_heap. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 #include <algorithm> #include <vector> 11 12 13 14 15 16 17 int main() { const int SIZE = 10; int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 }; std: : vector< int > v( a, a + SIZE ), v 2; std: : ostream_iterator< int > output( cout, " " ); 18 19 20 21 22 23 24 25 26 cout << "Vector v before make_heap: n" ; std: : copy( v. begin(), v. end(), output ); // create heap from vector v std: : make_heap( v. begin(), v. end() ); cout << "n. Vector v after make_heap: n"; std: : copy( v. begin(), v. end(), output ); Create a new heap. 136 fig 21_37. cpp (1 of 3)
27 28 29 30 31 32 137 // sort elements of v with sort_heap std: : sort_heap( v. begin(), v. end() ); cout << "n. Vector v after sort_heap: n"; std: : copy( v. begin(), v. end(), output ); 33 34 35 36 // perform the heapsort with push_heap and pop_heap cout << "nn. Array a contains: "; std: : copy( a, a + SIZE, output ); 37 38 cout << endl; 39 40 41 42 43 44 45 46 47 48 49 50 51 // place elements of array a into v 2 and Add elements // maintain elements of v 2 in heap for ( int i = 0; i < SIZE; ++i ) { v 2. push_back( a[ i ] ); std: : push_heap( v 2. begin(), v 2. end() ); cout << "nv 2 after push_heap(a[" << i << "]): "; std: : copy( v 2. begin(), v 2. end(), output ); } // end for cout << endl; one at a time. fig 21_37. cpp (2 of 3)
52 53 54 55 56 // remove elements from heap in sorted order for ( int j = 0; j < v 2. size(); ++j ) { cout << "nv 2 after " << v 2[ 0 ] << " popped from heapn"; std: : pop_heap( v 2. begin(), v 2. end() - j ); std: : copy( v 2. begin(), v 2. end(), output ); 57 58 } // end for 59 60 cout << endl; 61 62 return 0; 63 64 } // end main 138 fig 21_37. cpp (3 of 3)
139 Vector v before make_heap: 3 100 52 77 22 31 1 98 13 40 Vector v after make_heap: 100 98 52 77 40 31 1 3 13 22 Vector v after sort_heap: 1 3 13 22 31 40 52 77 98 100 Array a contains: 3 100 52 77 22 31 1 98 13 40 v 2 v 2 v 2 after after after push_heap(a[0]): push_heap(a[1]): push_heap(a[2]): push_heap(a[3]): push_heap(a[4]): push_heap(a[5]): push_heap(a[6]): push_heap(a[7]): push_heap(a[8]): push_heap(a[9]): 3 100 100 100 3 3 52 77 52 98 52 3 3 22 31 1 77 22 31 1 3 13 77 40 31 1 3 13 22 fig 21_37. cpp output (1 of 2)
v 2 after 100 popped from heap 98 77 52 22 40 31 1 3 13 100 v 2 after 98 popped from heap 77 40 52 22 13 31 1 3 98 100 v 2 after 77 popped from heap 52 40 31 22 13 3 1 77 98 100 v 2 after 52 popped from heap 40 22 31 1 13 3 52 77 98 100 v 2 after 40 popped from heap 31 22 3 1 13 40 52 77 98 100 v 2 after 31 popped from heap 22 13 3 1 31 40 52 77 98 100 v 2 after 22 popped from heap 13 1 3 22 31 40 52 77 98 100 v 2 after 13 popped from heap 3 1 13 22 31 40 52 77 98 100 v 2 after 3 popped from heap 1 3 13 22 31 40 52 77 98 100 v 2 after 1 popped from heap 1 3 13 22 31 40 52 77 98 100 140 fig 21_37. cpp output (2 of 2)
141 21. 5. 13 min and max • min(value 1, value 2) – Returns smaller element • max(value 1, value 2) – Returns larger element
1 2 3 // Fig. 21. 38: fig 21_38. cpp // Standard library algorithms min and max. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <algorithm> 9 10 11 12 13 14 15 16 17 18 19 int main() { cout << << 20 21 22 23 "The minimum of 12 and 7 is: " std: : min( 12, 7 ); "n. The maximum of 12 and 7 is: " std: : max( 12, 7 ); "n. The minimum of 'G' and 'Z' is: " std: : min( 'G', 'Z' ); "n. The maximum of 'G' and 'Z' is: " std: : max( 'G', 'Z' ) << endl; return 0; } // end main 142 fig 21_38. cpp (1 of 1)
The The minimum maximum of of 143 12 and 7 is: 7 12 and 7 is: 12 'G' and 'Z' is: G 'G' and 'Z' is: Z fig 21_38. cpp output (1 of 1)
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_copy adjacent_find partial_sort_copy stable_sort 144
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( bit. Number) set bit. Number to on b. set() all bits on b. reset(bit. Number) set bit. Number to off b. reset() all bits off b. flip(bit. Number) flip bit (on to off, off to on) b. flip() flip all bits b[bit. Number] returns reference to bit b. at(bit. Number) range checking, returns reference
146 21. 6 Class bitset • Operations b. test(bit. Number) 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 &= b 1 – Logical AND between b and b 1, result in b • b. to_string() convert to string • b. to_ulong() convert to long • • •
1 2 3 // Fig. 21. 40: fig 21_40. cpp // Using a bitset to demonstrate the Sieve of Eratosthenes. #include <iostream> 4 5 6 7 using std: : cin; using std: : cout; using std: : endl; 8 9 #include <iomanip> 10 11 using std: : setw; 12 13 14 #include <bitset> #include <cmath> 15 16 17 18 19 20 int main() { const int size = 1024; int value; std: : bitset< size > sieve; 21 22 23 sieve. flip(); // bitset class definition // sqrt prototype 147 fig 21_40. cpp (1 of 3)
24 25 // perform Sieve of Eratosthenes int final. Bit = sqrt( sieve. size() ) + 1; 26 27 for ( int i = 2; i < final. Bit; ++i ) 28 29 30 31 32 if ( sieve. test( i ) ) 148 Sieve of Eratosthenes: turn off bits for all multiples of a number. What bits remain are prime. for ( int j = 2 * i; j < size; j += i ) sieve. reset( j ); 33 34 cout << "The prime numbers in the range 2 to 1023 are: n" ; 35 36 37 // display prime numbers in range 2 -1023 for ( int k = 2, counter = 0; k < size; ++k ) 38 39 40 41 42 43 44 45 46 47 48 if ( sieve. test( k ) ) { cout << setw( 5 ) << k; if ( ++counter % 12 == 0 ) cout << 'n'; } // end outer if cout << endl; fig 21_40. cpp (2 of 3)
49 50 51 // get value from user to determine whether value is prime cout << "n. Enter a value from 1 to 1023 (-1 to end): " ; cin >> value; 52 53 while ( value != -1 ) { 54 55 56 57 58 59 60 61 if ( sieve[ value ] ) cout << value << " is a prime numbern"; else cout << value << " is not a prime numbern" ; cout << "n. Enter a value from 2 to 1023 (-1 to end): " ; cin >> value; 62 63 } // end while 64 65 return 0; 66 67 149 } // end main fig 21_40. cpp (3 of 3)
The prime numbers in the range 2 to 1023 are: 2 3 5 7 11 13 17 19 23 41 43 47 53 59 61 67 71 73 97 101 103 107 109 113 127 131 137 157 163 167 173 179 181 193 197 229 233 239 241 257 263 269 283 293 307 311 313 317 331 337 347 367 373 379 383 389 397 401 409 419 439 443 449 457 461 463 467 479 487 509 521 523 541 547 557 563 569 571 599 601 607 613 617 619 631 643 661 673 677 683 691 709 719 727 751 757 761 769 773 787 797 809 811 829 839 853 857 859 863 877 881 883 919 929 937 941 947 953 967 971 977 1009 1013 1019 1021 Enter a value from 1 to 1023 (-1 to end): 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 150 29 79 139 199 271 349 421 491 577 647 733 821 887 983 31 83 149 211 277 353 431 499 587 653 739 823 907 991 37 89 151 223 281 359 433 503 593 659 743 827 911 997 fig 21_40. cpp output (1 of 1)
151 21. 7 Function Objects • Function objects (<functional>) – Contain functions invoked using operator()
1 2 3 // Fig. 21. 42: fig 21_42. cpp // Demonstrating function objects. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 #include 12 13 14 15 16 17 18 19 20 <vector> <algorithm> <numeric> <functional> // // 152 vector class-template definition copy algorithm accumulate algorithm binary_function definition Create a function to be used andwith accumulate. fig 21_42. cpp // binary function adds square of its second argument // running total in its first argument, then returns sum int sum. Squares( int total, int value ) { return total + value * value; } // end function sum. Squares (1 of 4)
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 153 // binary function class template defines overloaded operator() // that adds suare of its second argument and running total in // its first argument, then returns sum template< class T > class Sum. Squares. Class : public std: : binary_function< T, T, T > { public: // add square of value to total and return result const T operator()( const T &total, const T &value ) { return total + value * value; } // end function operator() }; // end class Sum. Squares. Class Create a function object (it can also encapsulate data). Overload operator(). fig 21_42. cpp (2 of 4)
38 39 40 41 42 43 std: : vector< int > integers( array, array + SIZE ); 44 45 std: : ostream_iterator< int > output( cout, " " ); 46 47 int result = 0; 48 49 50 cout << "vector v contains: n"; std: : copy( integers. begin(), integers. end(), output ); 51 52 53 54 55 // calculate sum of squares of elements of vector integers // using binary function sum. Squares result = std: : accumulate( integers. begin(), integers. end(), 0, sum. Squares ); 56 57 58 cout << "nn. Sum of squares of elements in integers using " << "binarynfunction sum. Squares: " << result; 59 154 int main() { const int SIZE = 10; int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; accumulate initially passes 0 as the first argument, with the first element as the second. fig 21_42. cpp It then uses(3 theofreturn 4) value as the first argument, and iterates through the other elements.
60 61 62 63 // calculate sum of squares of elements of vector integers // using binary-function object result = std: : accumulate( integers. begin(), integers. end(), 0, Sum. Squares. Class< int >() ); 64 65 66 67 cout << "nn. Sum of squares of elements in integers using " << "binarynfunction object of type " << "Sum. Squares. Class< int >: " << result << endl; 68 69 return 0; 70 71 Use accumulate with a function object. } // 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 sum. Squares: 385 Sum of squares of elements in integers using binary function object of type Sum. Squares. Class< int >: 385 155 fig 21_42. cpp (4 of 4) fig 21_42. cpp output (1 of 1)
- Slides: 155