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 Container Adapters 21.4.1 stack Adapter 21.4.2 queue Adapter 21.4.3 priority_queue Adapter 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 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 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 STL Container Classes (Fig. 21.1) • Sequence containers – vector – deque – list • Associative containers – – – – set multiset map multimap • Container adapters – stack – queue – priority_queue 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 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 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 21.5: fig21_05.cpp // Demonstrating input and output with iterators. #include <iostream> fig21_05.cpp (1 of 2) using std::cout; using std::cin; using std::endl; #include <iterator> 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 // create istream_iterator for reading int values from cin std::istream_iterator< int > inputInt( cin ); int number1 = *inputInt; // read int from standard input ++inputInt; // move iterator to next input value int number2 = *inputInt; // read int from standard input Access and assign the iterator like a pointer. 22 23 24 25 26 27 28 29 30 31 // create ostream_iterator for writing int values to cout std::ostream_iterator< int > outputInt( cout ); cout << "The sum is: "; *outputInt = number1 + number2; cout << endl; // output result to cout fig21_05.cpp output (1 of 1) return 0; } // end main Enter two integers: 12 25 The sum is: 37 fig21_05.cpp (2 of 2) Create an ostream_iterator is similar. Assigning to this iterator outputs to cout. 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 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 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 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 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 21.2 Sequence Containers • Three sequence containers – vector - based on arrays – deque - based on arrays – list - robust linked list 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 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 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.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 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.14: fig21_14.cpp // Demonstrating standard library vector class template. #include <iostream> fig21_14.cpp (1 of 3) using std::cout; using std::cin; using std::endl; #include <vector> // vector class-template definition // prototype for function template printVector template < class T > void printVector( const std::vector< T > &integers2 ); int main() { Create a const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; std::vector< int > integers; cout << << << << vector of ints. Call member functions. "The initial size of integers is: " integers.size() "\nThe initial capacity of integers is: " integers.capacity(); 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // function push_back integers.push_back( 2 integers.push_back( 3 integers.push_back( 4 is in every sequence collection ); ); ); Add elements to end of vector using push_back. cout << "\nThe size of integers is: " << integers.size() << "\nThe capacity of integers is: " << integers.capacity(); cout << "\n\nOutput array using pointer notation: "; for ( int *ptr = array; ptr != array + SIZE; ++ptr ) cout << *ptr << ' '; cout << "\nOutput vector using iterator notation: "; printVector( integers ); cout << "\nReversed contents of vector integers: "; fig21_14.cpp (2 of 3) 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 std::vector< int >::reverse_iterator reverseIterator; for ( reverseIterator = integers.rbegin(); reverseIterator!= integers.rend(); ++reverseIterator ) cout << *reverseIterator << ' '; Walk through vector fig21_14.cpp backwards using (3 a of 3) reverse_iterator. cout << endl; return 0; } // end main // function template for outputting vector elements template < class T > void printVector( const std::vector< T > &integers2 ) { std::vector< T >::const_iterator constIterator; for ( constIterator = integers2.begin(); constIterator != integers2.end(); constIterator++ ) cout << *constIterator << ' '; } // end function printVector Template function to walk through vector forwards. The The The The 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 fig21_14.cpp output (1 of 1) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.15: fig21_15.cpp // Testing Standard Library vector class template // element-manipulation functions. #include <iostream> fig21_15.cpp (1 of 3) using std::cout; using std::endl; #include <vector> #include <algorithm> // vector class-template definition // copy algorithm int main() { const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; std::vector< int > integers( array, array + SIZE ); std::ostream_iterator< int > output( cout, " " ); Create vector (initialized using an array) and ostream_iterator. Copy range of iterators to output (ostream_iterator). cout << "Vector integers contains: "; std::copy( integers.begin(), integers.end(), output ); cout << "\nFirst element of integers: " << integers.front() << "\nLast element of integers: " << integers.back(); 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 integers[ 0 ] = 7; integers.at( 2 ) = 10; // set first element to 7 // set element at position 2 to 10 // insert 22 as 2nd element integers.insert( integers.begin() + 1, 22 ); More vector member fig21_15.cpp functions. (2 of 3) cout << "\n\nContents of vector integers after changes: "; std::copy( integers.begin(), integers.end(), output ); // access out-of-range element try { integers.at( 100 ) = 777; at has range checking, and can throw an exception. } // end try // catch out_of_range exception catch ( std::out_of_range outOfRange ) { cout << "\n\nException: " << outOfRange.what(); } // end catch // erase first element integers.erase( integers.begin() ); cout << "\n\nVector integers after erasing first element: "; std::copy( integers.begin(), integers.end(), output ); 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 // erase remaining elements integers.erase( integers.begin(), integers.end() ); cout << "\nAfter erasing all elements, vector integers " << ( integers.empty() ? "is" : "is not" ) << " empty"; // insert elements from array integers.insert( integers.begin(), array, array + SIZE ); cout << "\n\nContents of vector integers before clear: "; std::copy( integers.begin(), integers.end(), output ); // empty integers; clear calls erase to empty a collection integers.clear(); cout << "\nAfter clear, vector integers " << ( integers.empty() ? "is" : "is not" ) << " empty"; cout << endl; return 0; } // end main fig21_15.cpp (3 of 3) 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 fig21_15.cpp output (1 of 1) 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; 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 21.17: fig21_17.cpp // Standard library list class template test program. #include <iostream> fig21_17.cpp (1 of 5) using std::cout; using std::endl; #include <list> #include <algorithm> // list class-template definition // copy algorithm // prototype for function template printList template < class T > void printList( const std::list< T > &listRef ); int main() { const int SIZE = 4; int array[ SIZE ] = { 2, 6, 4, 8 }; std::list< int > values; std::list< int > otherValues; // insert items in values values.push_front( 1 ); values.push_front( 2 ); values.push_back( 4 ); values.push_back( 3 ); Create two list objects. 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 cout << "values contains: "; printList( values ); values.sort(); Various list member functions. // sort values cout << "\nvalues after sorting contains: "; printList( values ); // insert elements of array into otherValues otherValues.insert( otherValues.begin(), array, array + SIZE ); cout << "\nAfter insert, otherValues contains: "; printList( otherValues ); // remove otherValues elements and insert at end of values values.splice( values.end(), otherValues ); cout << "\nAfter splice, values contains: "; printList( values ); values.sort(); // sort values cout << "\nAfter sort, values contains: "; printList( values ); fig21_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 // insert elements of array into otherValues otherValues.insert( otherValues.begin(), array, array + SIZE ); otherValues.sort(); cout << "\nAfter insert, otherValues contains: "; printList( otherValues ); // remove otherValues elements and insert into values // in sorted order values.merge( otherValues ); cout << "\nAfter merge:\n values contains: "; printList( values ); cout << "\n otherValues contains: "; printList( otherValues ); values.pop_front(); values.pop_back(); // remove element from front // remove element from back cout << "\nAfter pop_front and pop_back:" << "\n values contains: "; printList( values ); values.unique(); // remove duplicate elements cout << "\nAfter unique, values contains: "; printList( values ); fig21_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 // swap elements of values and otherValues values.swap( otherValues ); cout << "\nAfter swap:\n values contains: "; printList( values ); cout << "\n otherValues contains: "; printList( otherValues ); // replace contents of values with elements of otherValues values.assign( otherValues.begin(), otherValues.end() ); cout << "\nAfter assign, values contains: "; printList( values ); // remove otherValues elements and insert into values // in sorted order values.merge( otherValues ); cout << "\nAfter merge, values contains: "; printList( values ); values.remove( 4 ); // remove all 4s cout << "\nAfter remove( 4 ), values contains: "; printList( values ); fig21_17.cpp (4 of 5) 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 cout << endl; return 0; } // end main // printList function template definition; uses // ostream_iterator and copy algorithm to output list elements template < class T > void printList( const std::list< T > &listRef ) { if ( listRef.empty() ) cout << "List is empty"; else { std::ostream_iterator< T > output( cout, " " ); std::copy( listRef.begin(), listRef.end(), output ); } // end else } // end function printList fig21_17.cpp (5 of 5) values contains: 2 1 4 3 values after sorting contains: 1 2 3 4 After insert, otherValues contains: 2 6 4 8 After splice, values contains: 1 2 3 4 2 6 4 8 After sort, values contains: 1 2 2 3 4 4 6 8 After insert, otherValues contains: 2 4 6 8 After merge: values contains: 1 2 2 2 3 4 4 4 6 6 8 8 otherValues contains: List is empty After pop_front and pop_back: values contains: 2 2 2 3 4 4 4 6 6 8 After unique, values contains: 2 3 4 6 8 After swap: values contains: List is empty otherValues contains: 2 3 4 6 8 After assign, values contains: 2 3 4 6 8 After merge, values contains: 2 2 3 3 4 4 6 6 8 8 After remove( 4 ), values contains: 2 2 3 3 6 6 8 8 fig21_17.cpp output (1 of 1) 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 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.18: fig21_18.cpp // Standard library class deque test program. #include <iostream> fig21_18.cpp (1 of 2) using std::cout; using std::endl; #include <deque> #include <algorithm> // deque class-template definition // copy algorithm Create a deque, use member functions. int main() { std::deque< double > values; std::ostream_iterator< double > output( cout, " " ); // insert elements in values values.push_front( 2.2 ); values.push_front( 3.5 ); values.push_back( 1.1 ); cout << "values contains: "; // use subscript operator to obtain elements of values for ( int i = 0; i < values.size(); ++i ) cout << values[ i ] << ' '; 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 values.pop_front(); // remove first element cout << "\nAfter pop_front, values contains: "; std::copy( values.begin(), values.end(), output ); // use subscript operator to modify element at location 1 values[ 1 ] = 5.4; cout << "\nAfter 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 fig21_18.cpp (2 of 2) fig21_18.cpp output (1 of 1) 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 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 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.19: fig21_19.cpp // Testing Standard Library class multiset #include <iostream> fig21_19.cpp (1 of 3) using std::cout; using std::endl; #include <set> typedefs help clarify program. This declares an integer multiset that stores program values in ascending order. // multiset class-template definition // define short name for multiset type used in this typedef std::multiset< int, std::less< int > > ims; #include <algorithm> // copy algorithm int main() { const int SIZE = 10; int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 }; ims intMultiset; // ims is typedef for "integer multiset" std::ostream_iterator< int > output( cout, " " ); cout << "There are currently " << intMultiset.count( 15 ) << " values of 15 in the multiset\n"; 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 intMultiset.insert( 15 ); intMultiset.insert( 15 ); // insert 15 in intMultiset // insert 15 in intMultiset cout << "After inserts, there are " << intMultiset.count( 15 ) << " values of 15 in the multiset\n\n"; // iterator that cannot be used to change element values Use member function ims::const_iterator result; // find 15 in intMultiset; find returns iterator result = intMultiset.find( 15 ); if ( result != intMultiset.end() ) // if iterator not at end cout << "Found value 15\n"; // found search value 15 // find 20 in intMultiset; find returns iterator result = intMultiset.find( 20 ); if ( result == intMultiset.end() ) // will be true hence cout << "Did not find value 20\n"; // did not find 20 // insert elements of array a into intMultiset intMultiset.insert( a, a + SIZE ); cout << "\nAfter insert, intMultiset contains:\n"; std::copy( intMultiset.begin(), intMultiset.end(), output ); fig21_19.cpp (2 of 3) find. 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 // determine lower and upper bound of 22 in intMultiset cout << "\n\nLower bound of 22: " << *( intMultiset.lower_bound( 22 ) ); cout << "\nUpper bound of 22: " << *( intMultiset.upper_bound( 22 ) ); // p represents pair of const_iterators std::pair< ims::const_iterator, ims::const_iterator > p; // use equal_range to determine lower and // of 22 in intMultiset p = intMultiset.equal_range( 22 ); Use a pair object to get the and upper bound for upperlower bound 22. cout << "\n\nequal_range of 22:" << "\n Lower bound: " << *( p.first ) << "\n Upper bound: " << *( p.second ); cout << endl; return 0; } // end main fig21_19.cpp (3 of 3) There are currently 0 values of 15 in the multiset After inserts, there are 2 values of 15 in the multiset Found value 15 Did not find value 20 After insert, intMultiset contains: 1 7 9 13 15 15 18 22 22 30 85 100 Lower bound of 22: 22 Upper bound of 22: 30 equal_range of 22: Lower bound: 22 Upper bound: 30 fig21_19.cpp output (1 of 1) 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; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.20: fig21_20.cpp // Standard library class set test program. #include <iostream> fig21_20.cpp (1 of 3) using std::cout; using std::endl; #include <set> Create set. Syntax similar to multiset. // define short name for set type used in this program typedef std::set< double, std::less< double > > double_set; #include <algorithm> int main() { const int SIZE = 5; double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; double_set doubleSet( a, a + SIZE ); std::ostream_iterator< double > output( cout, " " ); cout << "doubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // p represents pair containing const_iterator and bool std::pair< double_set::const_iterator, bool > p; // insert 13.8 in doubleSet; insert returns pair in which // p.first represents location of 13.8 in doubleSet and // p.second represents whether 13.8 was insertedpair object has a value representing p = doubleSet.insert( 13.8 ); // value not in set fig21_20.cpp bool (2 of 3) whether or not the item was inserted. cout << "\n\n" << *( p.first ) << ( p.second ? " was" : " was not" ) << " inserted"; cout << "\ndoubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); // insert 9.5 in doubleSet p = doubleSet.insert( 9.5 ); // value already in set cout << "\n\n" << *( p.first ) << ( p.second ? " was" : " was not" ) << " inserted"; 46 47 48 49 50 51 52 53 cout << "\ndoubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); cout << endl; return 0; } // end main doubleSet contains: 2.1 3.7 4.2 9.5 13.8 was inserted doubleSet contains: 2.1 3.7 4.2 9.5 13.8 9.5 was not inserted doubleSet contains: 2.1 3.7 4.2 9.5 13.8 fig21_20.cpp (3 of 3) fig21_20.cpp output (1 of 1) 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.21: fig21_21.cpp // Standard library class multimap test program. #include <iostream> using std::cout; using std::endl; #include <map> // map class-template definition fig21_21.cpp Definition for a multimap (1 of 2) that maps integer keys to double values. // define short name for multimap type used in this program typedef std::multimap< int, double, std::less< int > > mmid; int main() { mmid pairs; Create multimap and insert key-value pairs. cout << "There are currently " << pairs.count( 15 ) << " pairs with key 15 in the multimap\n"; // insert two value_type objects in pairs 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 15\n\n"; 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // insert five value_type objects in pairs 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:\nKey\tValue\n"; fig21_21.cpp (2 of 2) print entire 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'; cout << endl; return 0; } // end main There are currently 0 pairs with key 15 in the multimap After inserts, there are 2 pairs with key 15 Multimap pairs contains: Key Value 5 77.54 10 22.22 15 2.7 15 99.3 20 9.345 25 33.333 30 111.11 fig21_21.cpp output (1 of 1) 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 > >; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.22: fig21_22.cpp // Standard library class map test program. #include <iostream> fig21_22.cpp (1 of 2) using std::cout; using std::endl; #include <map> Again, use typedefs to simplify declaration. // map class-template definition // define short name for map type used in this program typedef std::map< int, double, std::less< int > > mid; int main() { mid pairs; // insert eight value_type objects in pairs pairs.insert( mid::value_type( 15, 2.7 ) ); pairs.insert( mid::value_type( 30, 111.11 ) ); pairs.insert( mid::value_type( 5, 1010.1 ) ); pairs.insert( mid::value_type( 10, 22.22 ) ); pairs.insert( mid::value_type( 25, 33.333 ) ); 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 Duplicate keys ignored. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 cout << "pairs contains:\nKey\tValue\n"; // 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'; // use subscript operator to change pairs[ 25 ] = 9999.99; operator to add or change key-value value for key 25 pairs. // use subscript operator insert value for key 40 pairs[ 40 ] = 8765.43; cout << "\nAfter subscript operations, pairs contains:" << "\nKey\tValue\n"; for ( mid::const_iterator iter2 = pairs.begin(); iter2 != pairs.end(); ++iter2 ) cout << iter2->first << '\t' << iter2->second << '\n'; cout << endl; return 0; } // end main fig21_22.cpp (2 of 2) 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 fig21_22.cpp output (1 of 1) 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 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) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.23: fig21_23.cpp // Standard library adapter stack test program. #include <iostream> fig21_23.cpp (1 of 3) using std::cout; using std::endl; #include <stack> #include <vector> #include <list> // stack adapter definition // vector class-template definition // list class-template definition // popElements function-template prototype template< class T > void popElements( T &stackRef ); int main() { // stack with default underlying deque std::stack< int > intDequeStack; Create stacks with various implementations. // stack with underlying vector std::stack< int, std::vector< int > > intVectorStack; // stack with underlying list std::stack< int, std::list< int > > intListStack; 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // push the values 0-9 onto each stack for ( int i = 0; i < 10; ++i ) { intDequeStack.push( i ); intVectorStack.push( i ); intListStack.push( i ); Use member function push. fig21_23.cpp (2 of 3) } // end for // display and remove elements from each stack cout << "Popping from intDequeStack: "; popElements( intDequeStack ); cout << "\nPopping from intVectorStack: "; popElements( intVectorStack ); cout << "\nPopping from intListStack: "; popElements( intListStack ); cout << endl; return 0; } // end main 49 50 51 52 53 54 55 56 57 58 59 // pop elements from stack object to which stackRef refers template< class T > void popElements( T &stackRef ) { while ( !stackRef.empty() ) { cout << stackRef.top() << ' '; // view top element stackRef.pop(); // remove top element } // end while } // 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 fig21_23.cpp (3 of 3) fig21_23.cpp output (1 of 1) 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 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.24: fig21_24.cpp // Standard library adapter queue test program. #include <iostream> fig21_24.cpp (1 of 2) using std::cout; using std::endl; #include <queue> // 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. onto queue values ); ); ); cout << "Popping from values: "; while ( !values.empty() ) { cout << values.front() << ' '; values.pop(); } // end while // view front element // remove element 27 28 29 30 31 cout << endl; return 0; } // end main Popping from values: 3.2 9.8 5.4 fig21_24.cpp (2 of 2) fig21_24.cpp output (1 of 1) 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 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.25: fig21_25.cpp // Standard library adapter priority_queue test program. #include <iostream> fig21_25.cpp (1 of 2) using std::cout; using std::endl; #include <queue> // priority_queue adapter definition Create priority queue. int main() { std::priority_queue< double > priorities; // push elements priorities.push( priorities.push( 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 // view top element // remove top element 27 28 29 30 31 cout << endl; return 0; } // end main fig21_25.cpp (2 of 2) Popping from priorities: 9.8 5.4 3.2 fig21_25.cpp output (1 of 1) 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> 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, "" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 21.26: fig21_26.cpp // Standard library algorithms fill, fill_n, generate // and generate_n. #include <iostream> fig21_26.cpp (1 of 3) using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition char nextLetter(); // prototype Create vector of chars, to be used with various functions. int main() { std::vector< char > chars( 10 ); std::ostream_iterator< char > output( cout, " " ); // fill chars with 5s std::fill( chars.begin(), chars.end(), '5' ); cout << "Vector chars after filling with 5s:\n"; std::copy( chars.begin(), chars.end(), output ); Function fill. 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // fill first five elements of chars with As std::fill_n( chars.begin(), 5, 'A' ); cout << "\n\nVector chars after filling five elements" << " with As:\n"; std::copy( chars.begin(), chars.end(), output ); // generate values for all elements of chars with nextLetter std::generate( chars.begin(), chars.end(), nextLetter ); cout << "\n\nVector chars after generating letters A-J:\n"; std::copy( chars.begin(), chars.end(), output ); // generate values for first five elements of chars // with nextLetter std::generate_n( chars.begin(), 5, nextLetter ); cout << "\n\nVector chars after generating K-O for the" << " first five elements:\n"; std::copy( chars.begin(), chars.end(), output ); cout << endl; return 0; } // end main fig21_26.cpp Functions and (2generate of 3) generate_n use function nextLetter. 51 52 53 54 55 56 57 58 // returns next letter in the alphabet (starts with A) char nextLetter() { static char letter = 'A'; return letter++; } // end function nextLetter Vector chars after filling with 5s: 5 5 5 5 5 5 5 5 5 5 Vector chars after filling five elements with As: A A A A A 5 5 5 5 5 Vector chars after generating letters A-J: A B C D E F G H I J Vector chars after generating K-O for the first five elements: K L M N O F G H I J fig21_26.cpp (3 of 3) fig21_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(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); 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); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 21.27: fig21_27.cpp // Standard library functions equal, // mismatch and lexicographical_compare. #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition int main() { const int SIZE = 10; int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int a2[ SIZE ] = { 1, 2, 3, 4, 1000, 6, 7, 8, 9, 10 }; std::vector< int > v1( a1, a1 + SIZE ); std::vector< int > v2( a1, a1 + SIZE ); std::vector< int > v3( a2, a2 + SIZE ); std::ostream_iterator< int > output( cout, " " ); fig21_27.cpp (1 of 3) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 cout << "Vector v1 contains: "; std::copy( v1.begin(), v1.end(), output ); cout << "\nVector v2 contains: "; std::copy( v2.begin(), v2.end(), output ); cout << "\nVector v3 contains: "; std::copy( v3.begin(), v3.end(), output ); fig21_27.cpp (2 of 3) Use function equal. Compares all of v1 with v2. // compare vectors v1 and v2 for equality bool result = std::equal( v1.begin(), v1.end(), v2.begin() ); cout << "\n\nVector v1 " << ( result ? "is" : "is not" ) << " equal to vector v2.\n"; // compare vectors v1 and v3 for equality result = std::equal( v1.begin(), v1.end(), v3.begin() ); cout << "Vector v1 " << ( result ? "is" : "is not" ) << " equal to vector v3.\n"; // location represents pair of vector iterators std::pair< std::vector< int >::iterator, std::vector< int >::iterator > location; // check for mismatch between v1 and v3 location = std::mismatch( v1.begin(), v1.end(), v3.begin() ); Note use of function mismatch. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 cout << << << << << "\nThere is a mismatch between v1 and v3 at " "location " << ( location.first - v1.begin() ) "\nwhere v1 contains " << *location.first " and v3 contains " << *location.second "\n\n"; char c1[ SIZE ] = "HELLO"; char c2[ SIZE ] = "BYE BYE"; Use lexicographical_compare. // perform lexicographical comparison of c1 and c2 result = std::lexicographical_compare( c1, c1 + SIZE, c2, c2 + SIZE ); cout << c1 << ( result ? " is less than " : " is greater than or equal to " ) << c2 << endl; return 0; } // end main fig21_27.cpp (3 of 3) Vector v1 contains: 1 2 3 4 5 6 7 8 9 10 Vector v2 contains: 1 2 3 4 5 6 7 8 9 10 Vector v3 contains: 1 2 3 4 1000 6 7 8 9 10 Vector v1 is equal to vector v2. Vector v1 is not equal to vector v3. There is a mismatch between v1 and v3 at location 4 where v1 contains 5 and v3 contains 1000 HELLO is greater than or equal to BYE BYE fig21_27.cpp output (1 of 1) 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 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); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.28: fig21_28.cpp // Standard library functions remove, remove_if, // remove_copy and remove_copy_if. #include <iostream> fig21_28.cpp (1 of 4) using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition bool greater9( int ); // prototype 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 newLastElement; cout << "Vector v before removing all 10s:\n std::copy( v.begin(), v.end(), output ); "; 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // remove 10 from v newLastElement = std::remove( v.begin(), v.end(), 10 ); cout << "\nVector v after removing all 10s:\n "; std::copy( v.begin(), newLastElement, output ); Remove all 10's from v. fig21_28.cpp Returns an iterator (2 of 4) pointing to the new last element. std::vector< int > v2( a, a + SIZE ); std::vector< int > c( SIZE, 0 ); cout << "\n\nVector v2 before removing all 10s " << "and copying:\n "; std::copy( v2.begin(), v2.end(), output ); Use remove_copy to create a duplicate of v, with all the 10's removed. // copy from v2 to c, removing 10s in the process std::remove_copy( v2.begin(), v2.end(), c.begin(), 10 ); cout << "\nVector c after removing all 10s from v2:\n std::copy( c.begin(), c.end(), output ); std::vector< int > v3( a, a + SIZE ); cout << "\n\nVector v3 before removing all elements" << "\ngreater than 9:\n "; std::copy( v3.begin(), v3.end(), output ); "; 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 // remove elements greater than 9 from v3 newLastElement = std::remove_if( v3.begin(), v3.end(), greater9 ); cout << "\nVector v3 after removing all elements" << "\ngreater than 9:\n "; std::copy( v3.begin(), newLastElement, output ); fig21_28.cpp Use function greater9 to (3 of 4) determine whether to remove the element. std::vector< int > v4( a, a + SIZE ); std::vector< int > c2( SIZE, 0 ); cout << "\n\nVector v4 before removing all elements" << "\ngreater than 9 and copying:\n "; std::copy( v4.begin(), v4.end(), output ); Note use of remove_copy_if. // copy elements from v4 to c2, removing elements greater // than 9 in the process std::remove_copy_if( v4.begin(), v4.end(), c2.begin(), greater9 ); cout << "\nVector c2 after removing all elements" << "\ngreater than 9 from v4:\n "; std::copy( c2.begin(), c2.end(), output ); 76 77 78 79 80 81 82 83 84 85 86 87 cout << endl; return 0; } // end main // determine whether argument is greater than 9 bool greater9( int x ) { return x > 9; } // end greater9 fig21_28.cpp (4 of 4) Vector v before removing all 10s: 10 2 10 4 16 6 14 8 12 10 Vector v after removing all 10s: 2 4 16 6 14 8 12 Vector v2 before removing all 10s and copying: 10 2 10 4 16 6 14 8 12 10 Vector c after removing all 10s from v2: 2 4 16 6 14 8 12 0 0 0 Vector v3 before removing all elements greater than 9: 10 2 10 4 16 6 14 8 12 10 Vector v3 after removing all elements greater than 9: 2 4 6 8 Vector v4 before removing all elements greater than 9 and copying: 10 2 10 4 16 6 14 8 12 10 Vector c2 after removing all elements greater than 9 from v4: 2 4 6 8 0 0 0 0 0 0 fig21_28.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 21.29: fig21_29.cpp // Standard library functions replace, replace_if, // replace_copy and replace_copy_if. #include <iostream> fig21_29.cpp (1 of 4) using std::cout; using std::endl; #include <algorithm> #include <vector> bool greater9( int ); 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 > v1( a, a + SIZE ); cout << "Vector v1 before replacing all 10s:\n std::copy( v1.begin(), v1.end(), output ); "; 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // replace 10s in v1 with 100 std::replace( v1.begin(), v1.end(), 10, 100 ); cout << "\nVector v1 after replacing 10s with 100s:\n std::copy( v1.begin(), v1.end(), output ); Use functions replace, replace_copy. "; std::vector< int > v2( a, a + SIZE ); std::vector< int > c1( SIZE ); cout << "\n\nVector v2 before replacing all 10s " << "and copying:\n "; std::copy( v2.begin(), v2.end(), output ); // copy from v2 to c1, replacing 10s with 100s std::replace_copy( v2.begin(), v2.end(), c1.begin(), 10, 100 ); cout << "\nVector c1 after replacing all 10s in v2:\n std::copy( c1.begin(), c1.end(), output ); std::vector< int > v3( a, a + SIZE ); cout << "\n\nVector v3 before replacing values greater" << " than 9:\n "; std::copy( v3.begin(), v3.end(), output ); "; fig21_29.cpp (2 of 4) 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 // replace values greater than 9 in v3 with 100 std::replace_if( v3.begin(), v3.end(), greater9, 100 ); cout << "\nVector v3 after replacing all values greater" << "\nthan 9 with 100s:\n "; std::copy( v3.begin(), v3.end(), output ); std::vector< int > v4( a, a + SIZE ); std::vector< int > c2( SIZE ); cout << "\n\nVector v4 before replacing all values greater " << "than 9 and copying:\n "; std::copy( v4.begin(), v4.end(), output ); // copy v4 to c2, replacing elements greater than 9 with 100 std::replace_copy_if( v4.begin(), v4.end(), c2.begin(), greater9, 100 ); cout << "\nVector c2 after replacing all values greater " << "than 9 in v4:\n "; std::copy( c2.begin(), c2.end(), output ); cout << endl; return 0; } // end main fig21_29.cpp (3 of 4) 78 79 80 81 82 83 84 // determine whether argument is greater than 9 bool greater9( int x ) { return x > 9; } // end function greater9 Vector v1 before replacing all 10s: 10 2 10 4 16 6 14 8 12 10 Vector v1 after replacing 10s with 100s: 100 2 100 4 16 6 14 8 12 100 Vector v2 before replacing all 10s and copying: 10 2 10 4 16 6 14 8 12 10 Vector c1 after replacing all 10s in v2: 100 2 100 4 16 6 14 8 12 100 Vector v3 before replacing values greater than 9: 10 2 10 4 16 6 14 8 12 10 Vector v3 after replacing all values greater than 9 with 100s: 100 2 100 4 100 6 100 8 100 100 Vector v4 before replacing all values greater than 9 and copying: 10 2 10 4 16 6 14 8 12 10 Vector c2 after replacing all values greater than 9 in v4: 100 2 100 4 100 6 100 8 100 100 fig21_29.cpp (4 of 4) fig21_29.cpp output (1 of 1) 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.30: fig21_30.cpp // Mathematical algorithms of the standard library. #include <iostream> fig21_30.cpp (1 of 5) using std::cout; using std::endl; #include <algorithm> #include <numeric> #include <vector> // algorithm definitions // accumulate is defined here bool greater9( int ); void outputSquare( int ); int calculateCube( int ); int main() { const int SIZE = 10; int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::vector< int > v( a1, a1 + SIZE ); std::ostream_iterator< int > output( cout, " " ); cout << "Vector v before random_shuffle: "; std::copy( v.begin(), v.end(), output ); 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // shuffle elements of v std::random_shuffle( v.begin(), v.end() ); cout << "\nVector v after random_shuffle: "; std::copy( v.begin(), v.end(), output ); int a2[] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 }; std::vector< int > v2( a2, a2 + SIZE ); cout << "\n\nVector v2 contains: "; std::copy( v2.begin(), v2.end(), output ); // count number of elements in v2 with value 8 int result = std::count( v2.begin(), v2.end(), 8 ); std::cout << "\nNumber of elements matching 8: " << result; // count number of elements in v2 that are greater than 9 result = std::count_if( v2.begin(), v2.end(), greater9 ); cout << "\nNumber of elements greater than 9: " << result; fig21_30.cpp (2 of 5) 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 // locate minimum element in v2 cout << "\n\nMinimum element in Vector v2 is: " << *( std::min_element( v2.begin(), v2.end() ) ); // locate maximum element in v2 cout << "\nMaximum element in Vector v2 is: " << *( std::max_element( v2.begin(), v2.end() ) ); // calculate sum of elements in v cout << "\n\nThe total of the elements in Vector v is: " << std::accumulate( v.begin(), v.end(), 0 ); cout << "\n\nThe square of every integer in Vector v is:\n"; // output square of every element in v std::for_each( v.begin(), v.end(), outputSquare ); std::vector< int > cubes( SIZE ); // calculate cube of each element in v; // place results in cubes std::transform( v.begin(), v.end(), cubes.begin(), calculateCube ); fig21_30.cpp (3 of 5) 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 cout << "\n\nThe cube of every integer in Vector v is:\n"; std::copy( cubes.begin(), cubes.end(), output ); cout << endl; return 0; } // end main // determine whether argument is greater than 9 bool greater9( int value ) { return value > 9; } // end function greater9 // output square of argument void outputSquare( int value ) { cout << value * value << ' '; } // end function outputSquare fig21_30.cpp (4 of 5) 96 97 98 99 100 101 // return cube of argument int calculateCube( int value ) { return value * value * value; } // end function calculateCube Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10 Vector v after random_shuffle: 5 4 1 3 7 8 9 10 6 2 Vector v2 contains: 100 2 8 1 50 3 8 8 9 10 Number of elements matching 8: 3 Number of elements greater than 9: 3 Minimum element in Vector v2 is: 1 Maximum element in Vector v2 is: 100 The total of the elements in Vector v is: 55 The square of every integer in Vector v is: 25 16 1 9 49 64 81 100 36 4 The cube of every integer in Vector v is: 125 64 1 27 343 512 729 1000 216 8 fig21_30.cpp (5 of 5) fig21_30.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.31: fig21_31.cpp // Standard library search and sort algorithms. #include <iostream> fig21_31.cpp (1 of 4) using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition bool greater10( int value ); // prototype int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 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 ); 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 if ( location != v.end() ) cout << "\n\nFound 16 at location " << ( location - v.begin() ); else cout << "\n\n16 not found"; // locate first occurrence of 100 in v location = std::find( v.begin(), v.end(), 100 ); if ( location != v.end() ) cout << "\nFound 100 at location " << ( location - v.begin() ); else cout << "\n100 not found"; // locate first occurrence of value greater than 10 in v location = std::find_if( v.begin(), v.end(), greater10 ); if ( location != v.end() ) cout << "\n\nThe first value greater than 10 is " << *location << "\nfound at location " << ( location - v.begin() ); else cout << "\n\nNo values greater than 10 were found"; fig21_31.cpp (2 of 4) 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 // sort elements of v std::sort( v.begin(), v.end() ); cout << "\n\nVector v after sort: "; std::copy( v.begin(), v.end(), output ); // use binary_search to locate 13 in v if ( std::binary_search( v.begin(), v.end(), 13 ) ) cout << "\n\n13 was found in v"; else cout << "\n\n13 was not found in v"; // use binary_search to locate 100 in v if ( std::binary_search( v.begin(), v.end(), 100 ) ) cout << "\n100 was found in v"; else cout << "\n100 was not found in v"; cout << endl; return 0; } // end main fig21_31.cpp (3 of 4) 77 78 79 80 81 82 // determine whether argument is greater than 10 bool greater10( int value ) { return value > 10; } // end function greater10 Vector v contains: 10 2 17 5 16 8 13 11 20 7 Found 16 at location 4 100 not found The first value greater than 10 is 17 found at location 2 Vector v after sort: 2 5 7 8 10 11 13 16 17 20 13 was found in v 100 was not found in v fig21_31.cpp (4 of 4) fig21_31.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.32: fig21_32.cpp // Standard library algorithms iter_swap, swap and swap_ranges. #include <iostream> fig21_32.cpp (1 of 2) using std::cout; using std::endl; #include <algorithm> // algorithm definitions 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, " " ); cout << "Array a contains:\n "; std::copy( a, a + SIZE, output ); // swap elements at locations 0 and 1 of array a std::swap( a[ 0 ], a[ 1 ] ); cout << "\nArray a after swapping a[0] and a[1] " << "using swap:\n "; std::copy( a, a + SIZE, output ); 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // use iterators to swap elements at locations // 0 and 1 of array a std::iter_swap( &a[ 0 ], &a[ 1 ] ); cout << "\nArray a after swapping a[0] and a[1] " << "using iter_swap:\n "; std::copy( a, a + SIZE, output ); // swap elements in first five elements of array a with // elements in last five elements of array a std::swap_ranges( a, a + 5, a + 5 ); cout << "\nArray a after swapping the first five elements\n" << "with the last five elements:\n "; std::copy( a, a + SIZE, output ); cout << endl; return 0; } // end main fig21_32.cpp (2 of 2) 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 fig21_32.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.33: fig21_33.cpp // Standard library functions copy_backward, merge, // unique and reverse. #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition int main() { const int SIZE = 5; int a1[ SIZE ] = { 1, 3, 5, 7, 9 }; int a2[ SIZE ] = { 2, 4, 5, 7, 9 }; std::vector< int > v1( a1, a1 + SIZE ); std::vector< int > v2( a2, a2 + SIZE ); std::ostream_iterator< int > output( cout, " " ); cout << "Vector v1 contains: "; std::copy( v1.begin(), v1.end(), output ); cout << "\nVector v2 contains: "; std::copy( v2.begin(), v2.end(), output ); fig21_33.cpp (1 of 3) 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 std::vector< int > results( v1.size() ); // place elements of v1 into results in reverse order std::copy_backward( v1.begin(), v1.end(), results.end() ); cout << "\n\nAfter copy_backward, results contains: "; std::copy( results.begin(), results.end(), output ); std::vector< int > results2( v1.size() + v2.size() ); // merge elements of v1 and v2 into results2 in sorted order std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(), results2.begin() ); cout << "\n\nAfter merge of v1 and v2 results2 contains:\n"; std::copy( results2.begin(), results2.end(), output ); // eliminate duplicate values from results2 std::vector< int >::iterator endLocation; endLocation = std::unique( results2.begin(), results2.end() ); cout << "\n\nAfter unique results2 contains:\n"; std::copy( results2.begin(), endLocation, output ); fig21_33.cpp (2 of 3) 53 54 55 56 57 58 59 60 61 62 63 64 cout << "\n\nVector v1 after reverse: "; // reverse elements of v1 std::reverse( v1.begin(), v1.end() ); std::copy( v1.begin(), v1.end(), output ); fig21_33.cpp (3 of 3) cout << endl; return 0; } // 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 fig21_33.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 21.34: fig21_34.cpp // Standard library algorithms inplace_merge, // reverse_copy and unique_copy. #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> #include <iterator> // algorithm definitions // vector class-template definition // back_inserter definition int main() { const int SIZE = 10; int a1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 }; std::vector< int > v1( a1, a1 + SIZE ); std::ostream_iterator< int > output( cout, " " ); cout << "Vector v1 contains: "; std::copy( v1.begin(), v1.end(), output ); // merge first half of v1 with second half of v1 such that // v1 contains sorted set of elements after merge std::inplace_merge( v1.begin(), v1.begin() + 5, v1.end() ); fig21_34.cpp (1 of 2) 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 cout << "\nAfter inplace_merge, v1 contains: "; std::copy( v1.begin(), v1.end(), output ); std::vector< int > results1; // copy only unique elements of v1 into results1 std::unique_copy( v1.begin(), v1.end(), std::back_inserter( results1 ) ); cout << "\nAfter unique_copy results1 contains: "; std::copy( results1.begin(), results1.end(), output ); std::vector< int > results2; cout << "\nAfter reverse_copy, results2 contains: "; // copy elements of v1 into results2 in reverse order std::reverse_copy( v1.begin(), v1.end(), std::back_inserter( results2 ) ); std::copy( results2.begin(), results2.end(), output ); cout << endl; return 0; } // end main fig21_34.cpp (2 of 2) Vector v1 contains: 1 3 5 7 9 1 3 5 7 9 After inplace_merge, v1 contains: 1 1 3 3 5 5 7 7 9 9 After unique_copy results1 contains: 1 3 5 7 9 After reverse_copy, results2 contains: 9 9 7 7 5 5 3 3 1 1 fig21_34.cpp output (1 of 1) 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.35: fig21_35.cpp // Standard library algorithms includes, set_difference, // set_intersection, set_symmetric_difference and set_union. #include <iostream> using std::cout; using std::endl; #include <algorithm> // algorithm definitions int main() { const int SIZE1 = 10, SIZE2 = 5, SIZE3 = 20; int a1[ SIZE1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int a2[ SIZE2 ] = { 4, 5, 6, 7, 8 }; int a3[ SIZE2 ] = { 4, 5, 6, 11, 15 }; std::ostream_iterator< int > output( cout, " " ); cout << "a1 contains: "; std::copy( a1, a1 + SIZE1, output ); cout << "\na2 contains: "; std::copy( a2, a2 + SIZE2, output ); cout << "\na3 contains: "; std::copy( a3, a3 + SIZE2, output ); fig21_35.cpp (1 of 3) 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // determine whether set a2 is completely contained in a1 if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) ) cout << "\n\na1 includes a2"; else cout << "\n\na1 does not include a2"; // determine whether set a3 is completely contained in a1 if ( std::includes( a1, a1 + SIZE1, a3, a3 + SIZE2 ) ) cout << "\na1 includes a3"; else cout << "\na1 does not include a3"; int difference[ SIZE1 ]; // determine elements of a1 not in a2 int *ptr = std::set_difference( a1, a1 + SIZE1, a2, a2 + SIZE2, difference ); cout << "\n\nset_difference of a1 and a2 is: "; std::copy( difference, ptr, output ); int intersection[ SIZE1 ]; // determine elements in both a1 and a2 ptr = std::set_intersection( a1, a1 + SIZE1, a2, a2 + SIZE2, intersection ); fig21_35.cpp (2 of 3) 53 54 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 cout << "\n\nset_intersection of a1 and a2 is: "; std::copy( intersection, ptr, output ); int symmetric_difference[ SIZE1 ]; // determine elements of a1 that are not in a2 and // elements of a2 that are not in a1 ptr = std::set_symmetric_difference( a1, a1 + SIZE1, a2, a2 + SIZE2, symmetric_difference ); cout << "\n\nset_symmetric_difference of a1 and a2 is: "; std::copy( symmetric_difference, ptr, output ); int unionSet[ SIZE3 ]; // determine elements that are in either or both sets ptr = std::set_union( a1, a1 + SIZE1, a3, a3 + SIZE2, unionSet ); cout << "\n\nset_union of a1 and a3 is: "; std::copy( unionSet, ptr, output ); cout << endl; return 0; } // end main fig21_35.cpp (3 of 3) a1 contains: 1 2 3 4 5 6 7 8 9 10 a2 contains: 4 5 6 7 8 a3 contains: 4 5 6 11 15 a1 includes a2 a1 does not include a3 set_difference of a1 and a2 is: 1 2 3 9 10 set_intersection of a1 and a2 is: 4 5 6 7 8 set_symmetric_difference of a1 and 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 fig21_35.cpp output (1 of 1) 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 21.36: fig21_36.cpp // Standard library functions lower_bound, upper_bound and // equal_range for a sorted sequence of values. #include <iostream> fig21_36.cpp (1 of 4) using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition int main() { const int SIZE = 10; int a1[] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 }; std::vector< int > v( a1, a1 + SIZE ); std::ostream_iterator< int > output( cout, " " ); 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 ); 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 cout << "\n\nLower bound of 6 is element " << ( lower - v.begin() ) << " of vector v"; // determine upper-bound insertion point for 6 in v std::vector< int >::iterator upper; upper = std::upper_bound( v.begin(), v.end(), 6 ); cout << "\nUpper bound of 6 is element " << ( upper - v.begin() ) << " of vector v"; // 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 ); cout << << << cout << << "\nUsing 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"; cout << "\n\nUse lower_bound to locate the first point\n" << "at which 5 can be inserted in order"; fig21_36.cpp (2 of 4) 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 // determine lower-bound insertion point for 5 in v lower = std::lower_bound( v.begin(), v.end(), 5 ); cout << "\n Lower bound of 5 is element " << ( lower - v.begin() ) << " of vector v"; cout << "\n\nUse upper_bound to locate the last point\n" << "at which 7 can be inserted in order"; // determine upper-bound insertion point for 7 in v upper = std::upper_bound( v.begin(), v.end(), 7 ); cout << "\n Upper bound of 7 is element " << ( upper - v.begin() ) << " of vector v"; cout << "\n\nUse equal_range to locate the first and\n" << "last point at which 5 can be inserted in order"; // use equal_range to determine both the lower- and // upper-bound insertion points for 5 eq = std::equal_range( v.begin(), v.end(), 5 ); cout << << 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; fig21_36.cpp (3 of 4) 78 79 80 81 return 0; } // end main fig21_36.cpp (4 of 4) Vector v contains: 2 2 4 4 4 6 6 6 6 8 Lower bound of 6 is Upper bound of 6 is Using equal_range: Lower bound of 6 Upper bound of 6 element 5 of vector v element 9 of vector v is element 5 of vector v is element 9 of vector v Use lower_bound to locate the first point at which 5 can be inserted in order Lower bound of 5 is element 5 of vector v 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 fig21_36.cpp output (1 of 1) 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 21.37: fig21_37.cpp // Standard library algorithms push_heap, pop_heap, // make_heap and sort_heap. #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> 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 ), v2; std::ostream_iterator< int > output( cout, " " ); 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 << "\nVector v after make_heap:\n"; std::copy( v.begin(), v.end(), output ); Create a new heap. fig21_37.cpp (1 of 3) 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // sort elements of v with sort_heap std::sort_heap( v.begin(), v.end() ); fig21_37.cpp (2 of 3) cout << "\nVector v after sort_heap:\n"; std::copy( v.begin(), v.end(), output ); // perform the heapsort with push_heap and pop_heap cout << "\n\nArray a contains: "; std::copy( a, a + SIZE, output ); cout << endl; // place elements of array a into v2 and Add elements // maintain elements of v2 in heap for ( int i = 0; i < SIZE; ++i ) { v2.push_back( a[ i ] ); std::push_heap( v2.begin(), v2.end() ); cout << "\nv2 after push_heap(a[" << i << "]): "; std::copy( v2.begin(), v2.end(), output ); } // end for cout << endl; one at a time. 52 53 54 55 56 57 58 59 60 61 62 63 64 // remove elements from heap in sorted order for ( int j = 0; j < v2.size(); ++j ) { cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n"; std::pop_heap( v2.begin(), v2.end() - j ); std::copy( v2.begin(), v2.end(), output ); } // end for cout << endl; return 0; } // end main fig21_37.cpp (3 of 3) 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 fig21_37.cpp output (1 of 2) Array a contains: 3 100 52 77 22 31 1 98 13 40 v2 v2 v2 v2 v2 v2 v2 v2 v2 v2 after after after after after after after after after after push_heap(a[0]): push_heap(a[1]): push_heap(a[2]): push_heap(a[3]): push_heap(a[4]): push_heap(a[5]): push_heap(a[6]): push_heap(a[7]): push_heap(a[8]): push_heap(a[9]): 3 100 100 100 100 100 100 100 100 100 3 3 52 77 52 77 52 77 52 77 52 98 52 98 52 98 52 3 3 22 3 22 31 3 22 31 1 77 22 31 1 3 77 22 31 1 3 13 77 40 31 1 3 13 22 v2 after 100 popped from heap 98 77 52 22 40 31 1 3 13 100 v2 after 98 popped from heap 77 40 52 22 13 31 1 3 98 100 v2 after 77 popped from heap 52 40 31 22 13 3 1 77 98 100 v2 after 52 popped from heap 40 22 31 1 13 3 52 77 98 100 v2 after 40 popped from heap 31 22 3 1 13 40 52 77 98 100 v2 after 31 popped from heap 22 13 3 1 31 40 52 77 98 100 v2 after 22 popped from heap 13 1 3 22 31 40 52 77 98 100 v2 after 13 popped from heap 3 1 13 22 31 40 52 77 98 100 v2 after 3 popped from heap 1 3 13 22 31 40 52 77 98 100 v2 after 1 popped from heap 1 3 13 22 31 40 52 77 98 100 fig21_37.cpp output (2 of 2) 21.5.13 min and max • min(value1, value2) – Returns smaller element • max(value1, value2) – Returns larger element 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 21.38: fig21_38.cpp // Standard library algorithms min and max. #include <iostream> using std::cout; using std::endl; #include <algorithm> int main() { cout << << cout << << cout << << cout << << "The minimum of 12 and 7 is: " std::min( 12, 7 ); "\nThe maximum of 12 and 7 is: " std::max( 12, 7 ); "\nThe minimum of 'G' and 'Z' is: " std::min( 'G', 'Z' ); "\nThe maximum of 'G' and 'Z' is: " std::max( 'G', 'Z' ) << endl; return 0; } // end main fig21_38.cpp (1 of 1) The The The The minimum maximum minimum maximum of of of of 12 and 7 is: 7 12 and 7 is: 12 'G' and 'Z' is: G 'G' and 'Z' is: Z fig21_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 rotate_copy adjacent_find partial_sort partial_sort_copy stable_sort 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 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 21.40: fig21_40.cpp // Using a bitset to demonstrate the Sieve of Eratosthenes. #include <iostream> fig21_40.cpp (1 of 3) using std::cin; using std::cout; using std::endl; #include <iomanip> using std::setw; #include <bitset> #include <cmath> // bitset class definition // sqrt prototype int main() { const int size = 1024; int value; std::bitset< size > sieve; sieve.flip(); 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // perform Sieve of Eratosthenes int finalBit = sqrt( sieve.size() ) + 1; for ( int i = 2; i < finalBit; ++i ) if ( sieve.test( i ) ) Sieve of Eratosthenes: turn off bits for all multiples of a number. What bits remain are fig21_40.cpp prime. (2 of 3) for ( int j = 2 * i; j < size; j += i ) sieve.reset( j ); cout << "The prime numbers in the range 2 to 1023 are:\n"; // display prime numbers in range 2-1023 for ( int k = 2, counter = 0; k < size; ++k ) if ( sieve.test( k ) ) { cout << setw( 5 ) << k; if ( ++counter % 12 == 0 ) cout << '\n'; } // end outer if cout << endl; 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // get value from user to determine whether value is prime cout << "\nEnter a value from 1 to 1023 (-1 to end): "; cin >> value; while ( value != -1 ) { if ( sieve[ value ] ) cout << value << " is a prime number\n"; else cout << value << " is not a prime number\n"; cout << "\nEnter a value from 2 to 1023 (-1 to end): "; cin >> value; } // end while return 0; } // end main fig21_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 191 193 197 227 229 233 239 241 251 257 263 269 283 293 307 311 313 317 331 337 347 367 373 379 383 389 397 401 409 419 439 443 449 457 461 463 467 479 487 509 521 523 541 547 557 563 569 571 599 601 607 613 617 619 631 641 643 661 673 677 683 691 701 709 719 727 751 757 761 769 773 787 797 809 811 829 839 853 857 859 863 877 881 883 919 929 937 941 947 953 967 971 977 1009 1013 1019 1021 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 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 fig21_40.cpp output (1 of 1) 21.7 Function Objects • Function objects (<functional>) – Contain functions invoked using operator() STL func tio n o b jec 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Fig. 21.42: fig21_42.cpp // Demonstrating function objects. #include <iostream> using std::cout; using std::endl; #include #include #include #include <vector> <algorithm> <numeric> <functional> fig21_42.cpp (1 of 4) // // // // vector class-template definition copy algorithm accumulate algorithm binary_function definition Create a function to be used and with accumulate. // binary function adds square of its second argument // running total in its first argument, then returns sum int sumSquares( int total, int value ) { return total + value * value; } // end function sumSquares 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // 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 SumSquaresClass : 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 SumSquaresClass fig21_42.cpp Create a function (2 object of 4)(it can also encapsulate data). Overload operator(). 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 int main() { const int SIZE = 10; int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::vector< int > integers( array, array + SIZE ); fig21_42.cpp (3 of 4) std::ostream_iterator< int > output( cout, " " ); int result = 0; cout << "vector v contains:\n"; std::copy( integers.begin(), integers.end(), output ); // calculate sum of squares of elements of vector integers // using binary function sumSquares result = std::accumulate( integers.begin(), integers.end(), 0, sumSquares ); cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction sumSquares: " << result; accumulate initially passes 0 as the first argument, with the first element as the second. It then uses the return value as the first argument, and iterates through the other elements. 60 61 62 63 64 65 66 67 68 69 70 71 // calculate sum of squares of elements of vector integers // using binary-function object result = std::accumulate( integers.begin(), integers.end(), 0, SumSquaresClass< int >() ); cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction object of type " << "SumSquaresClass< int >: " << result << endl; return 0; 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 sumSquares: 385 Sum of squares of elements in integers using binary function object of type SumSquaresClass< int >: 385 fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1)
© Copyright 2025 Paperzz