Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 21 - Standard Template Library (STL)

Similar presentations


Presentation on theme: "Chapter 21 - Standard Template Library (STL)"— Presentation transcript:

1 Chapter 21 - Standard Template Library (STL)
Outline Introduction to the Standard Template Library (STL) Introduction to Containers Introduction to Iterators Introduction to Algorithms Sequence Containers vector Sequence Container list Sequence Container deque Sequence Container Associative Containers multiset Associative Container set Associative Container multimap Associative Container map Associative Container Container Adapters stack Adapter queue Adapter priority_queue Adapter

2 Chapter 21 - Standard Template Library (STL)
Algorithms fill, fill_n, generate and generate_n equal, mismatch and lexicographical_compare remove, remove_if, remove_copy and remove_copy_if replace, replace_if, replace_copy and replace_copy_if Mathematical Algorithms Basic Searching and Sorting Algorithms swap, iter_swap and swap_ranges copy_backward, merge, unique and reverse inplace_merge, unique_copy and reverse_copy Set Operations lower_bound, upper_bound and equal_range Heapsort min and max Algorithms Not Covered in This Chapter Class bitset Function Objects

3 21.1 Introduction to the Standard Template Library (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

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 Container adapters Near containers Similar to containers, with reduced functionality 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 max_size, size = < <= > >= == != swap Functions for first-class containers 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 > 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

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

11 fig21_05.cpp (2 of 2) fig21_05.cpp output (1 of 1)
// create ostream_iterator for writing int values to cout std::ostream_iterator< int > outputInt( cout ); 24 cout << "The sum is: "; *outputInt = number1 + number2; // output result to cout cout << endl; 28 return 0; 30 31 } // end main fig21_05.cpp (2 of 2) fig21_05.cpp output (1 of 1) Create an ostream_iterator is similar. Assigning to this iterator outputs to cout. Enter two integers: 12 25 The sum is: 37

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 = p1 p == p1, p != p1 Output iterators 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 < p1, p <= p1 p > p1, p >= p1

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 Three sequence containers
vector - based on arrays deque - based on arrays list - robust linked list

18 21.2.1 vector Sequence Container
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 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

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

22 21.2.1 vector Sequence Container
vector functions operations v.front(), v.back() Return first and last element v.[elementNumber] = value; Assign value to an element v.at[elementNumber] = value; As above, with range checking out_of_bounds exception

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

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

25 Add elements to end of vector using push_back.
// function push_back is in every sequence collection integers.push_back( 2 ); integers.push_back( 3 ); integers.push_back( 4 ); 31 cout << "\nThe size of integers is: " << integers.size() << "\nThe capacity of integers is: " << integers.capacity(); 35 cout << "\n\nOutput array using pointer notation: "; 37 for ( int *ptr = array; ptr != array + SIZE; ++ptr ) cout << *ptr << ' '; 40 cout << "\nOutput vector using iterator notation: "; printVector( integers ); 43 cout << "\nReversed contents of vector integers: "; 45 Add elements to end of vector using push_back. fig21_14.cpp (2 of 3)

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

27 fig21_14.cpp output (1 of 1) The initial size of v is: 0
The initial capacity of v is: 0 The size of v is: 3 The capacity of v is: 4 Contents of array a using pointer notation: 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)

28 Create vector (initialized using an array) and ostream_iterator.
// Fig : fig21_15.cpp // Testing Standard Library vector class template // element-manipulation functions. #include <iostream> 5 using std::cout; using std::endl; 8 #include <vector> // vector class-template definition 10 #include <algorithm> // copy algorithm 11 12 int main() 13 { const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; 16 std::vector< int > integers( array, array + SIZE ); std::ostream_iterator< int > output( cout, " " ); 19 cout << "Vector integers contains: "; std::copy( integers.begin(), integers.end(), output ); 22 cout << "\nFirst element of integers: " << integers.front() << "\nLast element of integers: " << integers.back(); 25 fig21_15.cpp (1 of 3) Create vector (initialized using an array) and ostream_iterator. Copy range of iterators to output (ostream_iterator).

29 More vector member functions. fig21_15.cpp (2 of 3)
integers[ 0 ] = 7; // set first element to 7 integers.at( 2 ) = 10; // set element at position 2 to 10 28 // insert 22 as 2nd element integers.insert( integers.begin() + 1, 22 ); 31 cout << "\n\nContents of vector integers after changes: "; std::copy( integers.begin(), integers.end(), output ); 34 // access out-of-range element try { integers.at( 100 ) = 777; 38 } // end try 40 // catch out_of_range exception catch ( std::out_of_range outOfRange ) { cout << "\n\nException: " << outOfRange.what(); 44 } // end catch 46 // erase first element integers.erase( integers.begin() ); cout << "\n\nVector integers after erasing first element: "; std::copy( integers.begin(), integers.end(), output ); 51 More vector member functions. fig21_15.cpp (2 of 3) at has range checking, and can throw an exception.

30 fig21_15.cpp (3 of 3) 52 // erase remaining elements
integers.erase( integers.begin(), integers.end() ); cout << "\nAfter erasing all elements, vector integers " << ( integers.empty() ? "is" : "is not" ) << " empty"; 56 // 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 ); 61 // empty integers; clear calls erase to empty a collection integers.clear(); cout << "\nAfter clear, vector integers " << ( integers.empty() ? "is" : "is not" ) << " empty"; 66 cout << endl; 68 return 0; 70 71 } // end main fig21_15.cpp (3 of 3)

31 fig21_15.cpp output (1 of 1) 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: Exception: invalid vector<T> subscript Vector integers after erasing first element: After erasing all elements, vector integers is empty Contents of vector integers before clear: After clear, vector integers is empty fig21_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, otherObject ); Inserts values from otherObject before iterator t.merge( otherObject ) Removes otherObject and inserts it into t, sorted t.unique() Removes duplicate elements

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

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

36 Various list member functions.
28 cout << "values contains: "; printList( values ); 31 values.sort(); // sort values 33 cout << "\nvalues after sorting contains: "; printList( values ); 36 // insert elements of array into otherValues otherValues.insert( otherValues.begin(), array, array + SIZE ); 40 cout << "\nAfter insert, otherValues contains: "; printList( otherValues ); 43 // remove otherValues elements and insert at end of values values.splice( values.end(), otherValues ); 46 cout << "\nAfter splice, values contains: "; printList( values ); 49 values.sort(); // sort values 51 cout << "\nAfter sort, values contains: "; printList( values ); 54 Various list member functions. fig21_17.cpp (2 of 5)

37 fig21_17.cpp (3 of 5) 55 // insert elements of array into otherValues
otherValues.insert( otherValues.begin(), array, array + SIZE ); otherValues.sort(); 59 cout << "\nAfter insert, otherValues contains: "; printList( otherValues ); 62 // remove otherValues elements and insert into values // in sorted order values.merge( otherValues ); 66 cout << "\nAfter merge:\n values contains: "; printList( values ); cout << "\n otherValues contains: "; printList( otherValues ); 71 values.pop_front(); // remove element from front values.pop_back(); // remove element from back 74 cout << "\nAfter pop_front and pop_back:" << "\n values contains: "; printList( values ); 78 values.unique(); // remove duplicate elements 80 cout << "\nAfter unique, values contains: "; printList( values ); fig21_17.cpp (3 of 5)

38 fig21_17.cpp (4 of 5) 83 84 // swap elements of values and otherValues
values.swap( otherValues ); 86 cout << "\nAfter swap:\n values contains: "; printList( values ); cout << "\n otherValues contains: "; printList( otherValues ); 91 // replace contents of values with elements of otherValues values.assign( otherValues.begin(), otherValues.end() ); 94 cout << "\nAfter assign, values contains: "; printList( values ); 97 // remove otherValues elements and insert into values // in sorted order values.merge( otherValues ); 101 cout << "\nAfter merge, values contains: "; printList( values ); 104 values.remove( 4 ); // remove all 4s 106 cout << "\nAfter remove( 4 ), values contains: "; printList( values ); fig21_17.cpp (4 of 5)

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

40 fig21_17.cpp output (1 of 1) values contains: 2 1 4 3
values after sorting contains: After insert, otherValues contains: After splice, values contains: After sort, values contains: After insert, otherValues contains: After merge: values contains: otherValues contains: List is empty After pop_front and pop_back: values contains: After unique, values contains: After swap: values contains: List is empty otherValues contains: After assign, values contains: After merge, values contains: After remove( 4 ), values contains: fig21_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)

42 Create a deque, use member functions.
// Fig : fig21_18.cpp // Standard library class deque test program. #include <iostream> 4 using std::cout; using std::endl; 7 #include <deque> // deque class-template definition #include <algorithm> // copy algorithm 10 11 int main() 12 { std::deque< double > values; std::ostream_iterator< double > output( cout, " " ); 15 // insert elements in values values.push_front( 2.2 ); values.push_front( 3.5 ); values.push_back( 1.1 ); 20 cout << "values contains: "; 22 // use subscript operator to obtain elements of values for ( int i = 0; i < values.size(); ++i ) cout << values[ i ] << ' '; 26 fig21_18.cpp (1 of 2) Create a deque, use member functions.

43 fig21_18.cpp (2 of 2) fig21_18.cpp output (1 of 1)
values.pop_front(); // remove first element 28 cout << "\nAfter pop_front, values contains: "; std::copy( values.begin(), values.end(), output ); 31 // use subscript operator to modify element at location 1 values[ 1 ] = 5.4; 34 cout << "\nAfter values[ 1 ] = 5.4, values contains: "; std::copy( values.begin(), values.end(), output ); 37 cout << endl; 39 return 0; 41 42 } // end main fig21_18.cpp (2 of 2) fig21_18.cpp output (1 of 1) values contains: After pop_front, values contains: After values[ 1 ] = 5.4, values contains:

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

45 21.3.1 multiset Associative Container
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

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 // Fig : fig21_19.cpp // Testing Standard Library class multiset #include <iostream> 4 using std::cout; using std::endl; 7 #include <set> // multiset class-template definition 9 10 // define short name for multiset type used in this program 11 typedef std::multiset< int, std::less< int > > ims; 12 13 #include <algorithm> // copy algorithm 14 15 int main() 16 { const int SIZE = 10; int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 }; 19 ims intMultiset; // ims is typedef for "integer multiset" std::ostream_iterator< int > output( cout, " " ); 22 cout << "There are currently " << intMultiset.count( 15 ) << " values of 15 in the multiset\n"; 25 fig21_19.cpp (1 of 3) typedefs help clarify program. This declares an integer multiset that stores values in ascending order.

49 Use member function find.
intMultiset.insert( 15 ); // insert 15 in intMultiset intMultiset.insert( 15 ); // insert 15 in intMultiset 28 cout << "After inserts, there are " << intMultiset.count( 15 ) << " values of 15 in the multiset\n\n"; 32 // iterator that cannot be used to change element values ims::const_iterator result; 35 // find 15 in intMultiset; find returns iterator result = intMultiset.find( 15 ); 38 if ( result != intMultiset.end() ) // if iterator not at end cout << "Found value 15\n"; // found search value 15 41 // find 20 in intMultiset; find returns iterator result = intMultiset.find( 20 ); 44 if ( result == intMultiset.end() ) // will be true hence cout << "Did not find value 20\n"; // did not find 20 47 // insert elements of array a into intMultiset intMultiset.insert( a, a + SIZE ); 50 cout << "\nAfter insert, intMultiset contains:\n"; std::copy( intMultiset.begin(), intMultiset.end(), output ); 53 fig21_19.cpp (2 of 3) Use member function find.

50 Use a pair object to get the lower and upper bound for 22.
// 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 ) ); 59 // p represents pair of const_iterators std::pair< ims::const_iterator, ims::const_iterator > p; 62 // use equal_range to determine lower and upper bound // of 22 in intMultiset p = intMultiset.equal_range( 22 ); 66 cout << "\n\nequal_range of 22:" << "\n Lower bound: " << *( p.first ) << "\n Upper bound: " << *( p.second ); 70 cout << endl; 72 return 0; 74 75 } // end main fig21_19.cpp (3 of 3) Use a pair object to get the lower and upper bound for 22.

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, intMultiset contains: 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)

52 21.3.2 set Associative Container
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 Create set. Syntax similar to multiset.
// Fig : fig21_20.cpp // Standard library class set test program. #include <iostream> 4 using std::cout; using std::endl; 7 #include <set> 9 10 // define short name for set type used in this program 11 typedef std::set< double, std::less< double > > double_set; 12 13 #include <algorithm> 14 15 int main() 16 { const int SIZE = 5; double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; 19 double_set doubleSet( a, a + SIZE ); std::ostream_iterator< double > output( cout, " " ); 22 cout << "doubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); 25 fig21_20.cpp (1 of 3) Create set. Syntax similar to multiset.

54 26 // p represents pair containing const_iterator and bool
std::pair< double_set::const_iterator, bool > p; 28 // 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 inserted p = doubleSet.insert( 13.8 ); // value not in set 33 cout << "\n\n" << *( p.first ) << ( p.second ? " was" : " was not" ) << " inserted"; 36 cout << "\ndoubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); 39 // insert 9.5 in doubleSet p = doubleSet.insert( 9.5 ); // value already in set 42 cout << "\n\n" << *( p.first ) << ( p.second ? " was" : " was not" ) << " inserted"; 45 fig21_20.cpp (2 of 3) pair object has a bool value representing whether or not the item was inserted.

55 fig21_20.cpp (3 of 3) fig21_20.cpp output (1 of 1)
cout << "\ndoubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); 48 cout << endl; 50 return 0; 52 53 } // end main fig21_20.cpp (3 of 3) fig21_20.cpp output (1 of 1) doubleSet contains: 13.8 was inserted doubleSet contains: 9.5 was not inserted

56 21.3.3 multimap Associative Container
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 > > 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

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

59 Use iterator to print entire multimap.
27 // insert five value_type objects in pairs pairs.insert( mmid::value_type( 30, ) ); pairs.insert( mmid::value_type( 10, ) ); pairs.insert( mmid::value_type( 25, ) ); pairs.insert( mmid::value_type( 20, ) ); pairs.insert( mmid::value_type( 5, ) ); 34 cout << "Multimap pairs contains:\nKey\tValue\n"; 36 // 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 cout << endl; 44 return 0; 46 47 } // end main fig21_21.cpp (2 of 2) Use iterator to print entire multimap.

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

61 21.3.4 map Associative Container
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] = ; Sets the value of key 30 to If subscript not in map, creates new key/value pair Type declaration std::map< int, double, std::less< int > >;

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

63 Can use subscript operator to add or change key-value pairs.
cout << "pairs contains:\nKey\tValue\n"; 28 // use const_iterator to walk through elements of pairs for ( mid::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter ) cout << iter->first << '\t' << iter->second << '\n'; 34 // use subscript operator to change value for key 25 pairs[ 25 ] = ; 37 // use subscript operator insert value for key 40 pairs[ 40 ] = ; 40 cout << "\nAfter subscript operations, pairs contains:" << "\nKey\tValue\n"; 43 for ( mid::const_iterator iter2 = pairs.begin(); iter2 != pairs.end(); ++iter2 ) cout << iter2->first << '\t' << iter2->second << '\n'; 48 cout << endl; 50 return 0; 52 53 } // end main fig21_22.cpp (2 of 2) Can use subscript operator to add or change key-value pairs.

64 fig21_22.cpp output (1 of 1) pairs contains: Key Value 5 1010.1
After subscript operations, pairs contains: fig21_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> > 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)

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

68 Use member function push. fig21_23.cpp (2 of 3)
// push the values 0-9 onto each stack for ( int i = 0; i < 10; ++i ) { intDequeStack.push( i ); intVectorStack.push( i ); intListStack.push( i ); 32 } // end for 34 // 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 ); 42 cout << endl; 44 return 0; 46 47 } // end main 48 Use member function push. fig21_23.cpp (2 of 3)

69 fig21_23.cpp (3 of 3) fig21_23.cpp output (1 of 1)
49 // pop elements from stack object to which stackRef refers 50 template< class T > 51 void popElements( T &stackRef ) 52 { while ( !stackRef.empty() ) { cout << stackRef.top() << ' '; // view top element stackRef.pop(); // remove top element 56 } // end while 58 59 } // end function popElements fig21_23.cpp (3 of 3) fig21_23.cpp output (1 of 1) Popping from intDequeStack: Popping from intVectorStack: Popping from intListStack:

70 21.4.2 queue Adapter queue Functions 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()

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

72 fig21_24.cpp (2 of 2) fig21_24.cpp output (1 of 1)
cout << endl; 28 return 0; 30 31 } // end main fig21_24.cpp (2 of 2) fig21_24.cpp output (1 of 1) Popping from values:

73 21.4.3 priority_queue Adapter
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()

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

75 fig21_25.cpp (2 of 2) fig21_25.cpp output (1 of 1)
cout << endl; 28 return 0; 30 31 } // end main fig21_25.cpp (2 of 2) fig21_25.cpp output (1 of 1) Popping from priorities:

76 STL separates containers and 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(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, ""

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

79 Functions generate and generate_n use function nextLetter.
// fill first five elements of chars with As std::fill_n( chars.begin(), 5, 'A' ); 27 cout << "\n\nVector chars after filling five elements" << " with As:\n"; std::copy( chars.begin(), chars.end(), output ); 31 // generate values for all elements of chars with nextLetter std::generate( chars.begin(), chars.end(), nextLetter ); 34 cout << "\n\nVector chars after generating letters A-J:\n"; std::copy( chars.begin(), chars.end(), output ); 37 // generate values for first five elements of chars // with nextLetter std::generate_n( chars.begin(), 5, nextLetter ); 41 cout << "\n\nVector chars after generating K-O for the" << " first five elements:\n"; std::copy( chars.begin(), chars.end(), output ); 45 cout << endl; 47 return 0; 49 50 } // end main fig21_26.cpp (2 of 3) Functions generate and generate_n use function nextLetter.

80 fig21_26.cpp (3 of 3) fig21_26.cpp output (1 of 1)
51 52 // returns next letter in the alphabet (starts with A) 53 char nextLetter() 54 { static char letter = 'A'; return letter++; 57 58 } // end function nextLetter fig21_26.cpp (3 of 3) fig21_26.cpp output (1 of 1) Vector chars after filling with 5s: Vector chars after filling five elements with As: A A A A A 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

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

82 21.5.2 equal, mismatch and lexicographical_compare
Functions to compare sequences of values lexicographical_compare Compare contents of two character arrays Returns true if element in first sequence smaller than corresponding element in second bool result = lexicographical_compare(iter1, iter2, iter3);

83 fig21_27.cpp (1 of 3) 1 // Fig. 21.27: fig21_27.cpp
// Standard library functions equal, // mismatch and lexicographical_compare. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { 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 }; 17 std::vector< int > v1( a1, a1 + SIZE ); std::vector< int > v2( a1, a1 + SIZE ); std::vector< int > v3( a2, a2 + SIZE ); 21 std::ostream_iterator< int > output( cout, " " ); 23 fig21_27.cpp (1 of 3)

84 Use function equal. Compares all of v1 with v2.
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 ); 30 // compare vectors v1 and v2 for equality bool result = std::equal( v1.begin(), v1.end(), v2.begin() ); 34 cout << "\n\nVector v1 " << ( result ? "is" : "is not" ) << " equal to vector v2.\n"; 37 // 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"; 42 // location represents pair of vector iterators std::pair< std::vector< int >::iterator, std::vector< int >::iterator > location; 46 // check for mismatch between v1 and v3 location = std::mismatch( v1.begin(), v1.end(), v3.begin() ); 50 fig21_27.cpp (2 of 3) Use function equal. Compares all of v1 with v2. Note use of function mismatch.

85 Use lexicographical_compare.
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"; 56 char c1[ SIZE ] = "HELLO"; char c2[ SIZE ] = "BYE BYE"; 59 // perform lexicographical comparison of c1 and c2 result = std::lexicographical_compare( c1, c1 + SIZE, c2, c2 + SIZE ); 63 cout << c1 << ( result ? " is less than " : " is greater than or equal to " ) << c2 << endl; 68 return 0; 70 71 } // end main fig21_27.cpp (3 of 3) Use lexicographical_compare.

86 fig21_27.cpp output (1 of 1) Vector v1 contains: 1 2 3 4 5 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)

87 21.5.3 remove, remove_if, remove_copy and remove_copy_if
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

88 21.5.3 remove, remove_if, remove_copy and remove_copy_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);

89 fig21_28.cpp (1 of 4) 1 // Fig. 21.28: fig21_28.cpp
// Standard library functions remove, remove_if, // remove_copy and remove_copy_if. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 12 bool greater9( int ); // prototype 13 14 int main() 15 { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; 18 std::ostream_iterator< int > output( cout, " " ); 20 std::vector< int > v( a, a + SIZE ); std::vector< int >::iterator newLastElement; 23 cout << "Vector v before removing all 10s:\n "; std::copy( v.begin(), v.end(), output ); 26 fig21_28.cpp (1 of 4)

90 Use remove_copy to create a duplicate of v, with all the 10's removed.
// remove 10 from v newLastElement = std::remove( v.begin(), v.end(), 10 ); 29 cout << "\nVector v after removing all 10s:\n "; std::copy( v.begin(), newLastElement, output ); 32 std::vector< int > v2( a, a + SIZE ); std::vector< int > c( SIZE, 0 ); 35 cout << "\n\nVector v2 before removing all 10s " << "and copying:\n "; std::copy( v2.begin(), v2.end(), output ); 39 // copy from v2 to c, removing 10s in the process std::remove_copy( v2.begin(), v2.end(), c.begin(), 10 ); 42 cout << "\nVector c after removing all 10s from v2:\n "; std::copy( c.begin(), c.end(), output ); 45 std::vector< int > v3( a, a + SIZE ); 47 cout << "\n\nVector v3 before removing all elements" << "\ngreater than 9:\n "; std::copy( v3.begin(), v3.end(), output ); 51 Remove all 10's from v. Returns an iterator pointing to the new last element. fig21_28.cpp (2 of 4) Use remove_copy to create a duplicate of v, with all the 10's removed.

91 Use function greater9 to determine whether to remove the element.
// remove elements greater than 9 from v3 newLastElement = std::remove_if( v3.begin(), v3.end(), greater9 ); 55 cout << "\nVector v3 after removing all elements" << "\ngreater than 9:\n "; std::copy( v3.begin(), newLastElement, output ); 59 std::vector< int > v4( a, a + SIZE ); std::vector< int > c2( SIZE, 0 ); 62 cout << "\n\nVector v4 before removing all elements" << "\ngreater than 9 and copying:\n "; std::copy( v4.begin(), v4.end(), output ); 66 // 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 ); 71 cout << "\nVector c2 after removing all elements" << "\ngreater than 9 from v4:\n "; std::copy( c2.begin(), c2.end(), output ); 75 Use function greater9 to determine whether to remove the element. fig21_28.cpp (3 of 4) Note use of remove_copy_if.

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

93 fig21_28.cpp output (1 of 1) Vector v before removing all 10s:
Vector v after removing all 10s: Vector v2 before removing all 10s and copying: Vector c after removing all 10s from v2: Vector v3 before removing all elements greater than 9: Vector v3 after removing all elements Vector v4 before removing all elements greater than 9 and copying: Vector c2 after removing all elements greater than 9 from v4: fig21_28.cpp output (1 of 1)

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

95 fig21_29.cpp (1 of 4) 1 // Fig. 21.29: fig21_29.cpp
// Standard library functions replace, replace_if, // replace_copy and replace_copy_if. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> 10 #include <vector> 11 12 bool greater9( int ); 13 14 int main() 15 { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; 18 std::ostream_iterator< int > output( cout, " " ); 20 std::vector< int > v1( a, a + SIZE ); cout << "Vector v1 before replacing all 10s:\n "; std::copy( v1.begin(), v1.end(), output ); 24 fig21_29.cpp (1 of 4)

96 Use functions replace, replace_copy.
// replace 10s in v1 with 100 std::replace( v1.begin(), v1.end(), 10, 100 ); 27 cout << "\nVector v1 after replacing 10s with 100s:\n "; std::copy( v1.begin(), v1.end(), output ); 30 std::vector< int > v2( a, a + SIZE ); std::vector< int > c1( SIZE ); 33 cout << "\n\nVector v2 before replacing all 10s " << "and copying:\n "; std::copy( v2.begin(), v2.end(), output ); 37 // copy from v2 to c1, replacing 10s with 100s std::replace_copy( v2.begin(), v2.end(), c1.begin(), 10, 100 ); 41 cout << "\nVector c1 after replacing all 10s in v2:\n "; std::copy( c1.begin(), c1.end(), output ); 44 std::vector< int > v3( a, a + SIZE ); 46 cout << "\n\nVector v3 before replacing values greater" << " than 9:\n "; std::copy( v3.begin(), v3.end(), output ); 50 Use functions replace, replace_copy. fig21_29.cpp (2 of 4)

97 51 // replace values greater than 9 in v3 with 100
std::replace_if( v3.begin(), v3.end(), greater9, 100 ); 53 cout << "\nVector v3 after replacing all values greater" << "\nthan 9 with 100s:\n "; std::copy( v3.begin(), v3.end(), output ); 57 std::vector< int > v4( a, a + SIZE ); std::vector< int > c2( SIZE ); 60 cout << "\n\nVector v4 before replacing all values greater " << "than 9 and copying:\n "; std::copy( v4.begin(), v4.end(), output ); 64 // copy v4 to c2, replacing elements greater than 9 with 100 std::replace_copy_if( v4.begin(), v4.end(), c2.begin(), greater9, 100 ); 68 cout << "\nVector c2 after replacing all values greater " << "than 9 in v4:\n "; std::copy( c2.begin(), c2.end(), output ); 72 cout << endl; 74 return 0; 76 77 } // end main fig21_29.cpp (3 of 4)

98 fig21_29.cpp (4 of 4) fig21_29.cpp output (1 of 1)
78 79 // determine whether argument is greater than 9 80 bool greater9( int x ) 81 { return x > 9; 83 84 } // end function greater9 fig21_29.cpp (4 of 4) fig21_29.cpp output (1 of 1) Vector v1 before replacing all 10s: Vector v1 after replacing 10s with 100s: Vector v2 before replacing all 10s and copying: Vector c1 after replacing all 10s in v2: Vector v3 before replacing values greater than 9: Vector v3 after replacing all values greater than 9 with 100s: Vector v4 before replacing all values greater than 9 and copying: Vector c2 after replacing all values greater than 9 in v4:

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

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

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

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

103 fig21_30.cpp (3 of 5) 49 // locate minimum element in v2
cout << "\n\nMinimum element in Vector v2 is: " << *( std::min_element( v2.begin(), v2.end() ) ); 52 // locate maximum element in v2 cout << "\nMaximum element in Vector v2 is: " << *( std::max_element( v2.begin(), v2.end() ) ); 56 // calculate sum of elements in v cout << "\n\nThe total of the elements in Vector v is: " << std::accumulate( v.begin(), v.end(), 0 ); 60 cout << "\n\nThe square of every integer in Vector v is:\n"; 62 // output square of every element in v std::for_each( v.begin(), v.end(), outputSquare ); 65 std::vector< int > cubes( SIZE ); 67 // 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)

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

105 fig21_30.cpp (5 of 5) fig21_30.cpp output (1 of 1)
96 // return cube of argument 97 int calculateCube( int value ) 98 { return value * value * value; 100 101 } // end function calculateCube fig21_30.cpp (5 of 5) fig21_30.cpp output (1 of 1) Vector v before random_shuffle: Vector v after random_shuffle: Vector v2 contains: 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: The cube of every integer in Vector v is:

106 21.5.6 Basic Searching and Sorting Algorithms
find(iter1, iter2, value) Returns iterator to first instance of value (in range) find_if(iter1, iter2, function) Like find Returns iterator when function returns true sort(iter1, iter2) Sorts elements in ascending order binary_search(iter1, iter2, value) Searches ascending sorted list for value Uses binary search

107 fig21_31.cpp (1 of 4) 1 // Fig. 21.31: fig21_31.cpp
// Standard library search and sort algorithms. #include <iostream> 4 using std::cout; using std::endl; 7 #include <algorithm> // algorithm definitions #include <vector> // vector class-template definition 10 11 bool greater10( int value ); // prototype 12 13 int main() 14 { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 17 std::vector< int > v( a, a + SIZE ); std::ostream_iterator< int > output( cout, " " ); 20 cout << "Vector v contains: "; std::copy( v.begin(), v.end(), output ); 23 // locate first occurrence of 16 in v std::vector< int >::iterator location; location = std::find( v.begin(), v.end(), 16 ); fig21_31.cpp (1 of 4)

108 fig21_31.cpp (2 of 4) 27 28 if ( location != v.end() )
cout << "\n\nFound 16 at location " << ( location - v.begin() ); else cout << "\n\n16 not found"; 33 // locate first occurrence of 100 in v location = std::find( v.begin(), v.end(), 100 ); 36 if ( location != v.end() ) cout << "\nFound 100 at location " << ( location - v.begin() ); else cout << "\n100 not found"; 42 // locate first occurrence of value greater than 10 in v location = std::find_if( v.begin(), v.end(), greater10 ); 45 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"; 52 fig21_31.cpp (2 of 4)

109 fig21_31.cpp (3 of 4) 53 // sort elements of v
std::sort( v.begin(), v.end() ); 55 cout << "\n\nVector v after sort: "; std::copy( v.begin(), v.end(), output ); 58 // 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"; 64 // 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"; 70 cout << endl; 72 return 0; 74 75 } // end main 76 fig21_31.cpp (3 of 4)

110 fig21_31.cpp (4 of 4) fig21_31.cpp output (1 of 1)
77 // determine whether argument is greater than 10 78 bool greater10( int value ) 79 { return value > 10; 81 82 } // end function greater10 fig21_31.cpp (4 of 4) fig21_31.cpp output (1 of 1) Vector v contains: Found 16 at location 4 100 not found The first value greater than 10 is 17 found at location 2 Vector v after sort: 13 was found in v 100 was not found in v

111 21.5.7 swap, iter_swap and swap_ranges
swap(element1, element2) Exchanges two values swap( a[ 0 ], a[ 1 ] ); iter_swap(iter1, iter2) Exchanges the values to which the iterators refer swap_ranges(iter1, iter2, iter3) Swap the elements from iter1-iter2 with elements beginning at iter3

112 fig21_32.cpp (1 of 2) 1 // Fig. 21.32: fig21_32.cpp
// Standard library algorithms iter_swap, swap and swap_ranges. #include <iostream> 4 using std::cout; using std::endl; 7 #include <algorithm> // algorithm definitions 9 10 int main() 11 { const int SIZE = 10; int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::ostream_iterator< int > output( cout, " " ); 15 cout << "Array a contains:\n "; std::copy( a, a + SIZE, output ); 18 // swap elements at locations 0 and 1 of array a std::swap( a[ 0 ], a[ 1 ] ); 21 cout << "\nArray a after swapping a[0] and a[1] " << "using swap:\n "; std::copy( a, a + SIZE, output ); 25 fig21_32.cpp (1 of 2)

113 26 // 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 ); 32 // 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 ); 36 cout << "\nArray a after swapping the first five elements\n" << "with the last five elements:\n "; std::copy( a, a + SIZE, output ); 40 cout << endl; 42 return 0; 44 45 } // end main fig21_32.cpp (2 of 2)

114 fig21_32.cpp output (1 of 1) Array a contains: 1 2 3 4 5 6 7 8 9 10
Array a after swapping a[0] and a[1] using swap: Array a after swapping a[0] and a[1] using iter_swap: Array a after swapping the first five elements with the last five elements: fig21_32.cpp output (1 of 1)

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

116 fig21_33.cpp (1 of 3) 1 // Fig. 21.33: fig21_33.cpp
// Standard library functions copy_backward, merge, // unique and reverse. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { const int SIZE = 5; int a1[ SIZE ] = { 1, 3, 5, 7, 9 }; int a2[ SIZE ] = { 2, 4, 5, 7, 9 }; 17 std::vector< int > v1( a1, a1 + SIZE ); std::vector< int > v2( a2, a2 + SIZE ); 20 std::ostream_iterator< int > output( cout, " " ); 22 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)

117 27 std::vector< int > results( v1.size() ); 29 // place elements of v1 into results in reverse order std::copy_backward( v1.begin(), v1.end(), results.end() ); 32 cout << "\n\nAfter copy_backward, results contains: "; std::copy( results.begin(), results.end(), output ); 35 std::vector< int > results2( v1.size() + v2.size() ); 37 // merge elements of v1 and v2 into results2 in sorted order std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(), results2.begin() ); 41 cout << "\n\nAfter merge of v1 and v2 results2 contains:\n"; std::copy( results2.begin(), results2.end(), output ); 44 // eliminate duplicate values from results2 std::vector< int >::iterator endLocation; endLocation = std::unique( results2.begin(), results2.end() ); 49 cout << "\n\nAfter unique results2 contains:\n"; std::copy( results2.begin(), endLocation, output ); 52 fig21_33.cpp (2 of 3)

118 fig21_33.cpp (3 of 3) fig21_33.cpp output (1 of 1)
cout << "\n\nVector v1 after reverse: "; 54 // reverse elements of v1 std::reverse( v1.begin(), v1.end() ); 57 std::copy( v1.begin(), v1.end(), output ); 59 cout << endl; 61 return 0; 63 64 } // end main fig21_33.cpp (3 of 3) fig21_33.cpp output (1 of 1) Vector v1 contains: Vector v2 contains: After copy_backward, results contains: After merge of v1 and v2 results2 contains: After unique results2 contains: Vector v1 after reverse:

119 21.5.9 inplace_merge, unique_copy and reverse_copy
inplace_merge(iter1, iter2, iter3) Merges two sorted sequences (iter1-iter2, iter2-iter3) inside the same container unique_copy(iter1, iter2, iter3) Copies all unique elements in sorted array (from iter1-iter2) into iter3 reverse_copy(iter1, iter2, iter3) Reverses elements in iter1-iter2, copies into iter3

120 fig21_34.cpp (1 of 2) 1 // Fig. 21.34: fig21_34.cpp
// Standard library algorithms inplace_merge, // reverse_copy and unique_copy. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 #include <iterator> // back_inserter definition 12 13 int main() 14 { const int SIZE = 10; int a1[ SIZE ] = { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9 }; std::vector< int > v1( a1, a1 + SIZE ); 18 std::ostream_iterator< int > output( cout, " " ); 20 cout << "Vector v1 contains: "; std::copy( v1.begin(), v1.end(), output ); 23 // 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() ); 27 fig21_34.cpp (1 of 2)

121 28 cout << "\nAfter inplace_merge, v1 contains: ";
std::copy( v1.begin(), v1.end(), output ); 30 std::vector< int > results1; 32 // copy only unique elements of v1 into results1 std::unique_copy( v1.begin(), v1.end(), std::back_inserter( results1 ) ); 36 cout << "\nAfter unique_copy results1 contains: "; std::copy( results1.begin(), results1.end(), output ); 39 std::vector< int > results2; 41 cout << "\nAfter reverse_copy, results2 contains: "; 43 // copy elements of v1 into results2 in reverse order std::reverse_copy( v1.begin(), v1.end(), std::back_inserter( results2 ) ); 47 std::copy( results2.begin(), results2.end(), output ); 49 cout << endl; 51 return 0; 53 54 } // end main fig21_34.cpp (2 of 2)

122 fig21_34.cpp output (1 of 1) Vector v1 contains: 1 3 5 7 9 1 3 5 7 9
After inplace_merge, v1 contains: After unique_copy results1 contains: After reverse_copy, results2 contains: fig21_34.cpp output (1 of 1)

123 21.5.10 Set Operations includes(iter1, iter2, iter3, iter4)
Returns true if iter1-iter2 contains iter3-iter4 Both ranges must be sorted a1: 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

124 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: a2: set_symmetric_difference: Both sets must be sorted set_union( iter1, iter2, iter3, iter4, iter5) Copies elements in either or both sets to iter5

125 fig21_35.cpp (1 of 3) 1 // Fig. 21.35: fig21_35.cpp
// Standard library algorithms includes, set_difference, // set_intersection, set_symmetric_difference and set_union. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 11 int main() 12 { 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, " " ); 18 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 ); 25 fig21_35.cpp (1 of 3)

126 26 // 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"; 31 // 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"; 37 int difference[ SIZE1 ]; 39 // determine elements of a1 not in a2 int *ptr = std::set_difference( a1, a1 + SIZE1, a2, a2 + SIZE2, difference ); 43 cout << "\n\nset_difference of a1 and a2 is: "; std::copy( difference, ptr, output ); 46 int intersection[ SIZE1 ]; 48 // determine elements in both a1 and a2 ptr = std::set_intersection( a1, a1 + SIZE1, a2, a2 + SIZE2, intersection ); 52 fig21_35.cpp (2 of 3)

127 53 cout << "\n\nset_intersection of a1 and a2 is: ";
std::copy( intersection, ptr, output ); 55 int symmetric_difference[ SIZE1 ]; 57 // 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 ); 62 cout << "\n\nset_symmetric_difference of a1 and a2 is: "; std::copy( symmetric_difference, ptr, output ); 65 int unionSet[ SIZE3 ]; 67 // determine elements that are in either or both sets ptr = std::set_union( a1, a1 + SIZE1, a3, a3 + SIZE2, unionSet ); 71 cout << "\n\nset_union of a1 and a3 is: "; std::copy( unionSet, ptr, output ); 74 cout << endl; 76 return 0; 78 79 } // end main fig21_35.cpp (3 of 3)

128 fig21_35.cpp output (1 of 1) a1 contains: 1 2 3 4 5 6 7 8 9 10
a1 includes a2 a1 does not include a3 set_difference of a1 and a2 is: set_intersection of a1 and a2 is: set_symmetric_difference of a1 and a2 is: set_union of a1 and a3 is: fig21_35.cpp output (1 of 1)

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

130 fig21_36.cpp (1 of 4) 1 // Fig. 21.36: fig21_36.cpp
// Standard library functions lower_bound, upper_bound and // equal_range for a sorted sequence of values. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { 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, " " ); 18 cout << "Vector v contains:\n"; std::copy( v.begin(), v.end(), output ); 21 // determine lower-bound insertion point for 6 in v std::vector< int >::iterator lower; lower = std::lower_bound( v.begin(), v.end(), 6 ); 25 fig21_36.cpp (1 of 4)

131 26 cout << "\n\nLower bound of 6 is element "
<< ( lower - v.begin() ) << " of vector v"; 28 // determine upper-bound insertion point for 6 in v std::vector< int >::iterator upper; upper = std::upper_bound( v.begin(), v.end(), 6 ); 32 cout << "\nUpper bound of 6 is element " << ( upper - v.begin() ) << " of vector v"; 35 // 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 cout << "\nUsing equal_range:\n" << " Lower bound of 6 is element " << ( eq.first - v.begin() ) << " of vector v"; cout << "\n Upper bound of 6 is element " << ( eq.second - v.begin() ) << " of vector v"; 47 cout << "\n\nUse lower_bound to locate the first point\n" << "at which 5 can be inserted in order"; 50 fig21_36.cpp (2 of 4)

132 51 // determine lower-bound insertion point for 5 in v
lower = std::lower_bound( v.begin(), v.end(), 5 ); 53 cout << "\n Lower bound of 5 is element " << ( lower - v.begin() ) << " of vector v"; 56 cout << "\n\nUse upper_bound to locate the last point\n" << "at which 7 can be inserted in order"; 59 // determine upper-bound insertion point for 7 in v upper = std::upper_bound( v.begin(), v.end(), 7 ); 62 cout << "\n Upper bound of 7 is element " << ( upper - v.begin() ) << " of vector v"; 65 cout << "\n\nUse equal_range to locate the first and\n" << "last point at which 5 can be inserted in order"; 68 // 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 cout << "\n Lower bound of 5 is element " << ( eq.first - v.begin() ) << " of vector v"; cout << "\n Upper bound of 5 is element " << ( eq.second - v.begin() ) << " of vector v" << endl; fig21_36.cpp (3 of 4)

133 fig21_36.cpp (4 of 4) fig21_36.cpp output (1 of 1)
78 return 0; 80 81 } // end main fig21_36.cpp (4 of 4) fig21_36.cpp output (1 of 1) Vector v contains: Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Using equal_range: 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 Upper bound of 5 is element 5 of vector v

134 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

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

136 fig21_37.cpp (1 of 3) Create a new heap. 1 // Fig. 21.37: fig21_37.cpp
// Standard library algorithms push_heap, pop_heap, // make_heap and sort_heap. #include <iostream> 5 using std::cout; using std::endl; 8 #include <algorithm> 10 #include <vector> 11 12 int main() 13 { 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, " " ); 18 cout << "Vector v before make_heap:\n"; std::copy( v.begin(), v.end(), output ); 21 // create heap from vector v std::make_heap( v.begin(), v.end() ); 24 cout << "\nVector v after make_heap:\n"; std::copy( v.begin(), v.end(), output ); fig21_37.cpp (1 of 3) Create a new heap.

137 Add elements one at a time.
27 // sort elements of v with sort_heap std::sort_heap( v.begin(), v.end() ); 30 cout << "\nVector v after sort_heap:\n"; std::copy( v.begin(), v.end(), output ); 33 // perform the heapsort with push_heap and pop_heap cout << "\n\nArray a contains: "; std::copy( a, a + SIZE, output ); 37 cout << endl; 39 // place elements of array a into v2 and // 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 ); 47 } // end for 49 cout << endl; 51 fig21_37.cpp (2 of 3) Add elements one at a time.

138 fig21_37.cpp (3 of 3) 52 // 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 ); 57 } // end for 59 cout << endl; 61 return 0; 63 64 } // end main fig21_37.cpp (3 of 3)

139 fig21_37.cpp output (1 of 2) Vector v before make_heap:
Vector v after make_heap: Vector v after sort_heap: Array a contains: v2 after push_heap(a[0]): 3 v2 after push_heap(a[1]): 100 3 v2 after push_heap(a[2]): v2 after push_heap(a[3]): v2 after push_heap(a[4]): v2 after push_heap(a[5]): v2 after push_heap(a[6]): v2 after push_heap(a[7]): v2 after push_heap(a[8]): v2 after push_heap(a[9]): fig21_37.cpp output (1 of 2)

140 fig21_37.cpp output (2 of 2) v2 after 100 popped from heap
v2 after 98 popped from heap v2 after 77 popped from heap v2 after 52 popped from heap v2 after 40 popped from heap v2 after 31 popped from heap v2 after 22 popped from heap v2 after 13 popped from heap v2 after 3 popped from heap v2 after 1 popped from heap fig21_37.cpp output (2 of 2)

141 21.5.13 min and max min(value1, value2) max(value1, value2)
Returns smaller element max(value1, value2) Returns larger element

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

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

144 21.5.14 Algorithms Not Covered in This Chapter
adjacent_difference inner_product partial_sum nth_element partition stable_partition next_permutation prev_permutation rotate rotate_copy adjacent_find partial_sort partial_sort_copy stable_sort

145 21.6 Class bitset Operations 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

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

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

148 24 // perform Sieve of Eratosthenes
int finalBit = sqrt( sieve.size() ) + 1; 26 for ( int i = 2; i < finalBit; ++i ) 28 if ( sieve.test( i ) ) 30 for ( int j = 2 * i; j < size; j += i ) sieve.reset( j ); 33 cout << "The prime numbers in the range 2 to 1023 are:\n"; 35 // display prime numbers in range for ( int k = 2, counter = 0; k < size; ++k ) 38 if ( sieve.test( k ) ) { cout << setw( 5 ) << k; 41 if ( ++counter % 12 == 0 ) cout << '\n'; 44 } // end outer if 46 cout << endl; 48 Sieve of Eratosthenes: turn off bits for all multiples of a number. What bits remain are prime. fig21_40.cpp (2 of 3)

149 49 // get value from user to determine whether value is prime
cout << "\nEnter a value from 1 to 1023 (-1 to end): "; cin >> value; 52 while ( value != -1 ) { 54 if ( sieve[ value ] ) cout << value << " is a prime number\n"; else cout << value << " is not a prime number\n"; 59 cout << "\nEnter a value from 2 to 1023 (-1 to end): "; cin >> value; 62 } // end while 64 return 0; 66 67 } // end main fig21_40.cpp (3 of 3)

150 The prime numbers in the range 2 to 1023 are:
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 fig21_40.cpp output (1 of 1)

151 Function objects (<functional>)
Contain functions invoked using operator()

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

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

154 38 int main() 39 { const int SIZE = 10; int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 42 std::vector< int > integers( array, array + SIZE ); 44 std::ostream_iterator< int > output( cout, " " ); 46 int result = 0; 48 cout << "vector v contains:\n"; std::copy( integers.begin(), integers.end(), output ); 51 // calculate sum of squares of elements of vector integers // using binary function sumSquares result = std::accumulate( integers.begin(), integers.end(), , sumSquares ); 56 cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction sumSquares: " << result; 59 fig21_42.cpp (3 of 4) 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.

155 fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1)
// calculate sum of squares of elements of vector integers // using binary-function object result = std::accumulate( integers.begin(), integers.end(), , SumSquaresClass< int >() ); 64 cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction object of type " << "SumSquaresClass< int >: " << result << endl; 68 return 0; 70 71 } // end main fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1) Use accumulate with a function object. vector v contains: Sum of squares of elements in integers using binary function sumSquares: 385 function object of type SumSquaresClass< int >: 385


Download ppt "Chapter 21 - Standard Template Library (STL)"

Similar presentations


Ads by Google