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

Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

Standard Template Library (STL)

Outline21.1 Introduction to the Standard Template Library (STL)

21.1.1 Introduction to Containers21.1.2 Introduction to Iterators21.1.3 Introduction to Algorithms

21.2 Sequence Containers21.2.1 vector Sequence Container21.2.2 list Sequence Container21.2.3 deque Sequence Container

21.3 Associative Containers21.3.1 multiset Associative Container21.3.2 set Associative Container21.3.3 multimap Associative Container21.3.4 map Associative Container

21.4 Container Adapters21.4.1 stack Adapter21.4.2 queue Adapter21.4.3 priority_queue Adapter

Page 2: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

Chapter 21 - Standard Template Library (STL)

21.5 Algorithms21.5.1 fill, fill_n, generate and generate_n21.5.2 equal, mismatch and lexicographical_compare21.5.3 remove, remove_if, remove_copy and

remove_copy_if21.5.4 replace, replace_if, replace_copy and

replace_copy_if21.5.5 Mathematical Algorithms21.5.6 Basic Searching and Sorting Algorithms21.5.7 swap, iter_swap and swap_ranges21.5.8 copy_backward, merge, unique and reverse21.5.9 inplace_merge, unique_copy and reverse_copy21.5.10 Set Operations21.5.11 lower_bound, upper_bound and

equal_range21.5.12 Heapsort21.5.13 min and max21.5.14 Algorithms Not Covered in This Chapter

21.6 Class bitset21.7 Function Objects

Page 3: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 4: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 5: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

STL Container Classes (Fig. 21.1)

• Sequence containers– vector– deque– list

• Associative containers– set– multiset– map– multimap

• Container adapters– stack– queue– priority_queue

Page 6: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 7: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 8: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 9: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 10: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_05.cpp(1 of 2)

1 // Fig. 21.5: fig21_05.cpp2 // Demonstrating input and output with iterators.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 #include <iterator> // ostream_iterator and istream_iterator10 11 int main()12 {13 cout << "Enter two integers: ";14 15 // create istream_iterator for reading int values from cin16 std::istream_iterator< int > inputInt( cin ); 17 18 int number1 = *inputInt; // read int from standard input19 ++inputInt; // move iterator to next input value20 int number2 = *inputInt; // read int from standard input21

Note creation of istream_iterator. For compilation reasons, we use std:: rather than a using statement.

Access and assign the iterator like a pointer.

Page 11: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_05.cpp(2 of 2)

fig21_05.cppoutput (1 of 1)

22 // create ostream_iterator for writing int values to cout23 std::ostream_iterator< int > outputInt( cout ); 24 25 cout << "The sum is: ";26 *outputInt = number1 + number2; // output result to cout27 cout << endl;28 29 return 0;30 31 } // end main

Enter two integers: 12 25The sum is: 37 Create an

ostream_iterator is similar. Assigning to this iterator outputs to cout.

Page 12: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 13: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 14: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 15: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 16: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 17: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

21.2 Sequence Containers

• Three sequence containers– vector - based on arrays– deque - based on arrays– list - robust linked list

Page 18: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 19: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 20: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 21: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 22: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 23: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 24: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_14.cpp(1 of 3)

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

Create a vector of ints.

Call member functions.

Page 25: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_14.cpp(2 of 3)

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

Add elements to end of vector using push_back.

Page 26: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_14.cpp(3 of 3)

46 std::vector< int >::reverse_iterator reverseIterator;47 48 for ( reverseIterator = integers.rbegin();49 reverseIterator!= integers.rend(); 50 ++reverseIterator ) 51 cout << *reverseIterator << ' '; 52 53 cout << endl;54 55 return 0;56 57 } // end main58 59 // function template for outputting vector elements 60 template < class T > 61 void printVector( const std::vector< T > &integers2 )62 { 63 std::vector< T >::const_iterator constIterator; 64 65 for ( constIterator = integers2.begin(); 66 constIterator != integers2.end(); 67 constIterator++ ) 68 cout << *constIterator << ' '; 69 70 } // end function printVector

Walk through vector backwards using a reverse_iterator.

Template function to walk through vector forwards.

Page 27: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_14.cppoutput (1 of 1)

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

Page 28: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_15.cpp(1 of 3)

1 // Fig. 21.15: fig21_15.cpp2 // Testing Standard Library vector class template 3 // element-manipulation functions.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <vector> // vector class-template definition10 #include <algorithm> // copy algorithm 11 12 int main()13 {14 const int SIZE = 6; 15 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };16 17 std::vector< int > integers( array, array + SIZE );18 std::ostream_iterator< int > output( cout, " " );19 20 cout << "Vector integers contains: ";21 std::copy( integers.begin(), integers.end(), output );22 23 cout << "\nFirst element of integers: " << integers.front()24 << "\nLast element of integers: " << integers.back();25

Create vector (initialized using an array) and ostream_iterator.

Copy range of iterators to output (ostream_iterator).

Page 29: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_15.cpp(2 of 3)

26 integers[ 0 ] = 7; // set first element to 7 27 integers.at( 2 ) = 10; // set element at position 2 to 1028 29 // insert 22 as 2nd element 30 integers.insert( integers.begin() + 1, 22 ); 31 32 cout << "\n\nContents of vector integers after changes: ";33 std::copy( integers.begin(), integers.end(), output );34 35 // access out-of-range element36 try {37 integers.at( 100 ) = 777; 38 39 } // end try40 41 // catch out_of_range exception42 catch ( std::out_of_range outOfRange ) {43 cout << "\n\nException: " << outOfRange.what();44 45 } // end catch46 47 // erase first element 48 integers.erase( integers.begin() );49 cout << "\n\nVector integers after erasing first element: ";50 std::copy( integers.begin(), integers.end(), output );51

More vector member functions.

at has range checking, and can throw an exception.

Page 30: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_15.cpp(3 of 3)

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

Page 31: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_15.cppoutput (1 of 1)

Vector integers contains: 1 2 3 4 5 6First element of integers: 1Last 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 6After erasing all elements, vector integers is empty Contents of vector integers before clear: 1 2 3 4 5 6After clear, vector integers is empty

Page 32: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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;

Page 33: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 34: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 35: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cpp(1 of 5)

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

Create two list objects.

Page 36: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cpp(2 of 5)

28 29 cout << "values contains: ";30 printList( values );31 32 values.sort(); // sort values33 34 cout << "\nvalues after sorting contains: ";35 printList( values );36 37 // insert elements of array into otherValues38 otherValues.insert( otherValues.begin(), 39 array, array + SIZE ); 40 41 cout << "\nAfter insert, otherValues contains: ";42 printList( otherValues );43 44 // remove otherValues elements and insert at end of values45 values.splice( values.end(), otherValues ); 46 47 cout << "\nAfter splice, values contains: ";48 printList( values );49 50 values.sort(); // sort values51 52 cout << "\nAfter sort, values contains: ";53 printList( values );54

Various list member functions.

Page 37: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cpp(3 of 5)

55 // insert elements of array into otherValues56 otherValues.insert( otherValues.begin(), 57 array, array + SIZE ); 58 otherValues.sort(); 59 60 cout << "\nAfter insert, otherValues contains: ";61 printList( otherValues );62 63 // remove otherValues elements and insert into values64 // in sorted order 65 values.merge( otherValues ); 66 67 cout << "\nAfter merge:\n values contains: ";68 printList( values );69 cout << "\n otherValues contains: ";70 printList( otherValues );71 72 values.pop_front(); // remove element from front73 values.pop_back(); // remove element from back 74 75 cout << "\nAfter pop_front and pop_back:" 76 << "\n values contains: ";77 printList( values );78 79 values.unique(); // remove duplicate elements80 81 cout << "\nAfter unique, values contains: ";82 printList( values );

Page 38: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cpp(4 of 5)

83 84 // swap elements of values and otherValues85 values.swap( otherValues ); 86 87 cout << "\nAfter swap:\n values contains: ";88 printList( values );89 cout << "\n otherValues contains: ";90 printList( otherValues );91 92 // replace contents of values with elements of otherValues93 values.assign( otherValues.begin(), otherValues.end() ); 94 95 cout << "\nAfter assign, values contains: ";96 printList( values );97 98 // remove otherValues elements and insert into values99 // in sorted order 100 values.merge( otherValues ); 101 102 cout << "\nAfter merge, values contains: ";103 printList( values ); 104 105 values.remove( 4 ); // remove all 4s106 107 cout << "\nAfter remove( 4 ), values contains: ";108 printList( values );

Page 39: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cpp(5 of 5)

109 110 cout << endl;111 112 return 0;113 114 } // end main115 116 // printList function template definition; uses 117 // ostream_iterator and copy algorithm to output list elements118 template < class T >119 void printList( const std::list< T > &listRef )120 {121 if ( listRef.empty() )122 cout << "List is empty";123 124 else {125 std::ostream_iterator< T > output( cout, " " );126 std::copy( listRef.begin(), listRef.end(), output );127 128 } // end else129 130 } // end function printList

Page 40: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_17.cppoutput (1 of 1)

values contains: 2 1 4 3values after sorting contains: 1 2 3 4After insert, otherValues contains: 2 6 4 8After splice, values contains: 1 2 3 4 2 6 4 8After sort, values contains: 1 2 2 3 4 4 6 8After insert, otherValues contains: 2 4 6 8After merge: values contains: 1 2 2 2 3 4 4 4 6 6 8 8 otherValues contains: List is emptyAfter pop_front and pop_back: values contains: 2 2 2 3 4 4 4 6 6 8After unique, values contains: 2 3 4 6 8After swap: values contains: List is empty otherValues contains: 2 3 4 6 8After assign, values contains: 2 3 4 6 8After merge, values contains: 2 2 3 3 4 4 6 6 8 8After remove( 4 ), values contains: 2 2 3 3 6 6 8 8

Page 41: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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)

Page 42: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_18.cpp(1 of 2)

1 // Fig. 21.18: fig21_18.cpp2 // Standard library class deque test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <deque> // deque class-template definition9 #include <algorithm> // copy algorithm10 11 int main()12 { 13 std::deque< double > values;14 std::ostream_iterator< double > output( cout, " " );15 16 // insert elements in values17 values.push_front( 2.2 ); 18 values.push_front( 3.5 ); 19 values.push_back( 1.1 ); 20 21 cout << "values contains: ";22 23 // use subscript operator to obtain elements of values24 for ( int i = 0; i < values.size(); ++i )25 cout << values[ i ] << ' ';26

Create a deque, use member functions.

Page 43: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_18.cpp(2 of 2)

fig21_18.cppoutput (1 of 1)

27 values.pop_front(); // remove first element28 29 cout << "\nAfter pop_front, values contains: ";30 std::copy( values.begin(), values.end(), output );31 32 // use subscript operator to modify element at location 133 values[ 1 ] = 5.4; 34 35 cout << "\nAfter values[ 1 ] = 5.4, values contains: ";36 std::copy( values.begin(), values.end(), output );37 38 cout << endl;39 40 return 0;41 42 } // end main

values contains: 3.5 2.2 1.1After pop_front, values contains: 2.2 1.1After values[ 1 ] = 5.4, values contains: 2.2 5.4

Page 44: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 45: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 46: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 47: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 48: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_19.cpp(1 of 3)

1 // Fig. 21.19: fig21_19.cpp2 // Testing Standard Library class multiset3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <set> // multiset class-template definition9 10 // define short name for multiset type used in this program11 typedef std::multiset< int, std::less< int > > ims; 12 13 #include <algorithm> // copy algorithm14 15 int main()16 {17 const int SIZE = 10;18 int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 };19 20 ims intMultiset; // ims is typedef for "integer multiset"21 std::ostream_iterator< int > output( cout, " " );22 23 cout << "There are currently " << intMultiset.count( 15 )24 << " values of 15 in the multiset\n";25

typedefs help clarify program. This declares an integer multiset that stores values in ascending order.

Page 49: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_19.cpp(2 of 3)

26 intMultiset.insert( 15 ); // insert 15 in intMultiset27 intMultiset.insert( 15 ); // insert 15 in intMultiset28 29 cout << "After inserts, there are " 30 << intMultiset.count( 15 )31 << " values of 15 in the multiset\n\n";32 33 // iterator that cannot be used to change element values34 ims::const_iterator result; 35 36 // find 15 in intMultiset; find returns iterator37 result = intMultiset.find( 15 ); 38 39 if ( result != intMultiset.end() ) // if iterator not at end40 cout << "Found value 15\n"; // found search value 1541 42 // find 20 in intMultiset; find returns iterator43 result = intMultiset.find( 20 ); 44 45 if ( result == intMultiset.end() ) // will be true hence46 cout << "Did not find value 20\n"; // did not find 2047 48 // insert elements of array a into intMultiset49 intMultiset.insert( a, a + SIZE ); 50 51 cout << "\nAfter insert, intMultiset contains:\n";52 std::copy( intMultiset.begin(), intMultiset.end(), output );53

Use member function find.

Page 50: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_19.cpp(3 of 3)

54 // determine lower and upper bound of 22 in intMultiset55 cout << "\n\nLower bound of 22: " 56 << *( intMultiset.lower_bound( 22 ) );57 cout << "\nUpper bound of 22: " 58 << *( intMultiset.upper_bound( 22 ) );59 60 // p represents pair of const_iterators 61 std::pair< ims::const_iterator, ims::const_iterator > p;62 63 // use equal_range to determine lower and upper bound64 // of 22 in intMultiset 65 p = intMultiset.equal_range( 22 ); 66 67 cout << "\n\nequal_range of 22:"68 << "\n Lower bound: " << *( p.first )69 << "\n Upper bound: " << *( p.second );70 71 cout << endl;72 73 return 0;74 75 } // end main

Use a pair object to get the lower and upper bound for 22.

Page 51: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_19.cppoutput (1 of 1)

There are currently 0 values of 15 in the multisetAfter inserts, there are 2 values of 15 in the multiset Found value 15Did not find value 20 After insert, intMultiset contains:1 7 9 13 15 15 18 22 22 30 85 100 Lower bound of 22: 22Upper bound of 22: 30 equal_range of 22: Lower bound: 22 Upper bound: 30

Page 52: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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;

Page 53: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_20.cpp(1 of 3)

1 // Fig. 21.20: fig21_20.cpp2 // Standard library class set test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <set>9 10 // define short name for set type used in this program11 typedef std::set< double, std::less< double > > double_set;12 13 #include <algorithm>14 15 int main()16 {17 const int SIZE = 5;18 double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; 19 20 double_set doubleSet( a, a + SIZE );21 std::ostream_iterator< double > output( cout, " " );22 23 cout << "doubleSet contains: ";24 std::copy( doubleSet.begin(), doubleSet.end(), output );25

Create set. Syntax similar to multiset.

Page 54: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_20.cpp(2 of 3)

26 // p represents pair containing const_iterator and bool27 std::pair< double_set::const_iterator, bool > p; 28 29 // insert 13.8 in doubleSet; insert returns pair in which30 // p.first represents location of 13.8 in doubleSet and 31 // p.second represents whether 13.8 was inserted 32 p = doubleSet.insert( 13.8 ); // value not in set 33 34 cout << "\n\n" << *( p.first ) 35 << ( p.second ? " was" : " was not" ) << " inserted";36 37 cout << "\ndoubleSet contains: ";38 std::copy( doubleSet.begin(), doubleSet.end(), output );39 40 // insert 9.5 in doubleSet 41 p = doubleSet.insert( 9.5 ); // value already in set42 43 cout << "\n\n" << *( p.first ) 44 << ( p.second ? " was" : " was not" ) << " inserted";45

pair object has a bool value representing whether or not the item was inserted.

Page 55: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_20.cpp(3 of 3)

fig21_20.cppoutput (1 of 1)

46 cout << "\ndoubleSet contains: ";47 std::copy( doubleSet.begin(), doubleSet.end(), output );48 49 cout << endl;50 51 return 0;52 53 } // end main

doubleSet contains: 2.1 3.7 4.2 9.5 13.8 was inserteddoubleSet contains: 2.1 3.7 4.2 9.5 13.8 9.5 was not inserteddoubleSet contains: 2.1 3.7 4.2 9.5 13.8

Page 56: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 57: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

21.3.3 multimap Associative Container

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

Page 58: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_21.cpp(1 of 2)

1 // Fig. 21.21: fig21_21.cpp2 // Standard library class multimap test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <map> // map class-template definition9 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 {15 mmid pairs;16 17 cout << "There are currently " << pairs.count( 15 )18 << " pairs with key 15 in the multimap\n";19 20 // insert two value_type objects in pairs 21 pairs.insert( mmid::value_type( 15, 2.7 ) ); 22 pairs.insert( mmid::value_type( 15, 99.3 ) );23 24 cout << "After inserts, there are " 25 << pairs.count( 15 )26 << " pairs with key 15\n\n";

Definition for a multimap that maps integer keys to double values.

Create multimap and insert key-value pairs.

Page 59: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_21.cpp(2 of 2)

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

Use iterator to print entire multimap.

Page 60: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_21.cppoutput (1 of 1)

There are currently 0 pairs with key 15 in the multimapAfter inserts, there are 2 pairs with key 15 Multimap pairs contains:Key Value5 77.5410 22.2215 2.715 99.320 9.34525 33.33330 111.11

Page 61: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 62: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_22.cpp(1 of 2)

1 // Fig. 21.22: fig21_22.cpp2 // Standard library class map test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <map> // map class-template definition9 10 // define short name for map type used in this program11 typedef std::map< int, double, std::less< int > > mid;12 13 int main()14 {15 mid pairs;16 17 // insert eight value_type objects in pairs 18 pairs.insert( mid::value_type( 15, 2.7 ) ); 19 pairs.insert( mid::value_type( 30, 111.11 ) ); 20 pairs.insert( mid::value_type( 5, 1010.1 ) ); 21 pairs.insert( mid::value_type( 10, 22.22 ) ); 22 pairs.insert( mid::value_type( 25, 33.333 ) ); 23 pairs.insert( mid::value_type( 5, 77.54 ) ); // dupe ignored24 pairs.insert( mid::value_type( 20, 9.345 ) ); 25 pairs.insert( mid::value_type( 15, 99.3 ) ); // dupe ignored26

Again, use typedefs to simplify declaration.

Duplicate keys ignored.

Page 63: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_22.cpp(2 of 2)

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

Can use subscript operator to add or change key-value pairs.

Page 64: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_22.cppoutput (1 of 1)

pairs contains:Key Value5 1010.110 22.22 15 2.720 9.34525 33.33330 111.11 After subscript operations, pairs contains:Key Value5 1010.110 22.2215 2.720 9.34525 9999.9930 111.1140 8765.43

Page 65: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 66: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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)

Page 67: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_23.cpp(1 of 3)

1 // Fig. 21.23: fig21_23.cpp2 // Standard library adapter stack test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <stack> // stack adapter definition9 #include <vector> // vector class-template definition10 #include <list> // list class-template definition11 12 // popElements function-template prototype 13 template< class T >14 void popElements( T &stackRef );15 16 int main()17 {18 // stack with default underlying deque19 std::stack< int > intDequeStack; 20 21 // stack with underlying vector 22 std::stack< int, std::vector< int > > intVectorStack;23 24 // stack with underlying list 25 std::stack< int, std::list< int > > intListStack;26

Create stacks with various implementations.

Page 68: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_23.cpp(2 of 3)

27 // push the values 0-9 onto each stack 28 for ( int i = 0; i < 10; ++i ) {29 intDequeStack.push( i ); 30 intVectorStack.push( i );31 intListStack.push( i ); 32 33 } // end for34 35 // display and remove elements from each stack36 cout << "Popping from intDequeStack: ";37 popElements( intDequeStack );38 cout << "\nPopping from intVectorStack: ";39 popElements( intVectorStack );40 cout << "\nPopping from intListStack: ";41 popElements( intListStack );42 43 cout << endl;44 45 return 0;46 47 } // end main48

Use member function push.

Page 69: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_23.cpp(3 of 3)

fig21_23.cppoutput (1 of 1)

49 // pop elements from stack object to which stackRef refers50 template< class T >51 void popElements( T &stackRef )52 {53 while ( !stackRef.empty() ) {54 cout << stackRef.top() << ' '; // view top element 55 stackRef.pop(); // remove top element56 57 } // end while58 59 } // end function popElements

Popping from intDequeStack: 9 8 7 6 5 4 3 2 1 0Popping from intVectorStack: 9 8 7 6 5 4 3 2 1 0Popping from intListStack: 9 8 7 6 5 4 3 2 1 0

Page 70: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 71: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_24.cpp(1 of 2)

1 // Fig. 21.24: fig21_24.cpp2 // Standard library adapter queue test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <queue> // queue adapter definition9 10 int main()11 {12 std::queue< double > values;13 14 // push elements onto queue values15 values.push( 3.2 ); 16 values.push( 9.8 ); 17 values.push( 5.4 ); 18 19 cout << "Popping from values: ";20 21 while ( !values.empty() ) {22 cout << values.front() << ' '; // view front element23 values.pop(); // remove element 24 25 } // end while26

Create queue, add values using push.

Page 72: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_24.cpp(2 of 2)

fig21_24.cppoutput (1 of 1)

27 cout << endl;28 29 return 0;30 31 } // end main

Popping from values: 3.2 9.8 5.4

Page 73: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 74: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_25.cpp(1 of 2)

1 // Fig. 21.25: fig21_25.cpp2 // Standard library adapter priority_queue test program.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <queue> // priority_queue adapter definition9 10 int main()11 {12 std::priority_queue< double > priorities;13 14 // push elements onto priorities15 priorities.push( 3.2 ); 16 priorities.push( 9.8 ); 17 priorities.push( 5.4 ); 18 19 cout << "Popping from priorities: ";20 21 while ( !priorities.empty() ) {22 cout << priorities.top() << ' '; // view top element 23 priorities.pop(); // remove top element24 25 } // end while26

Create priority queue.

Insert items using push. When using pop, highest priority (largest) items removed first.

Page 75: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_25.cpp(2 of 2)

fig21_25.cppoutput (1 of 1)

27 cout << endl;28 29 return 0;30 31 } // end main

Popping from priorities: 9.8 5.4 3.2

Page 76: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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>

Page 77: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 78: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_26.cpp(1 of 3)

1 // Fig. 21.26: fig21_26.cpp2 // Standard library algorithms fill, fill_n, generate3 // and generate_n.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <algorithm> // algorithm definitions10 #include <vector> // vector class-template definition11 12 char nextLetter(); // prototype13 14 int main()15 {16 std::vector< char > chars( 10 );17 std::ostream_iterator< char > output( cout, " " );18 19 // fill chars with 5s 20 std::fill( chars.begin(), chars.end(), '5' );21 22 cout << "Vector chars after filling with 5s:\n";23 std::copy( chars.begin(), chars.end(), output );24

Create vector of chars, to be used with various functions.

Function fill.

Page 79: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_26.cpp(2 of 3)

25 // fill first five elements of chars with As26 std::fill_n( chars.begin(), 5, 'A' ); 27 28 cout << "\n\nVector chars after filling five elements"29 << " with As:\n";30 std::copy( chars.begin(), chars.end(), output );31 32 // generate values for all elements of chars with nextLetter33 std::generate( chars.begin(), chars.end(), nextLetter ); 34 35 cout << "\n\nVector chars after generating letters A-J:\n";36 std::copy( chars.begin(), chars.end(), output );37 38 // generate values for first five elements of chars39 // with nextLetter 40 std::generate_n( chars.begin(), 5, nextLetter ); 41 42 cout << "\n\nVector chars after generating K-O for the"43 << " first five elements:\n";44 std::copy( chars.begin(), chars.end(), output );45 46 cout << endl;47 48 return 0;49 50 } // end main

Functions generate and generate_n use function nextLetter.

Page 80: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_26.cpp(3 of 3)

fig21_26.cppoutput (1 of 1)

51 52 // returns next letter in the alphabet (starts with A)53 char nextLetter() 54 {55 static char letter = 'A'; 56 return letter++;57 58 } // 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

Page 81: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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 itempair < iterator, iterator > myPairObject;myPairObject = mismatch( iter1, iter2, iter3);

Page 82: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 83: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_27.cpp(1 of 3)

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

Page 84: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_27.cpp(2 of 3)

24 cout << "Vector v1 contains: ";25 std::copy( v1.begin(), v1.end(), output );26 cout << "\nVector v2 contains: ";27 std::copy( v2.begin(), v2.end(), output );28 cout << "\nVector v3 contains: ";29 std::copy( v3.begin(), v3.end(), output );30 31 // compare vectors v1 and v2 for equality 32 bool result = 33 std::equal( v1.begin(), v1.end(), v2.begin() );34 35 cout << "\n\nVector v1 " << ( result ? "is" : "is not" ) 36 << " equal to vector v2.\n";37 38 // compare vectors v1 and v3 for equality 39 result = std::equal( v1.begin(), v1.end(), v3.begin() );40 cout << "Vector v1 " << ( result ? "is" : "is not" ) 41 << " equal to vector v3.\n";42 43 // location represents pair of vector iterators44 std::pair< std::vector< int >::iterator,45 std::vector< int >::iterator > location;46 47 // check for mismatch between v1 and v3 48 location = 49 std::mismatch( v1.begin(), v1.end(), v3.begin() );50

Use function equal. Compares all of v1 with v2.

Note use of function mismatch.

Page 85: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_27.cpp(3 of 3)

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

Use lexicographical_compare.

Page 86: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_27.cppoutput (1 of 1)

Vector v1 contains: 1 2 3 4 5 6 7 8 9 10Vector v2 contains: 1 2 3 4 5 6 7 8 9 10Vector 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 4where v1 contains 5 and v3 contains 1000 HELLO is greater than or equal to BYE BYE

Page 87: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 88: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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 trueremove_copy_if(iter1, iter2, iter3, function);

Page 89: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_28.cpp(1 of 4)

1 // Fig. 21.28: fig21_28.cpp2 // Standard library functions remove, remove_if,3 // remove_copy and remove_copy_if.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <algorithm> // algorithm definitions10 #include <vector> // vector class-template definition11 12 bool greater9( int ); // prototype13 14 int main()15 { 16 const int SIZE = 10;17 int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };18 19 std::ostream_iterator< int > output( cout, " " );20 21 std::vector< int > v( a, a + SIZE ); 22 std::vector< int >::iterator newLastElement;23 24 cout << "Vector v before removing all 10s:\n ";25 std::copy( v.begin(), v.end(), output );26

Page 90: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_28.cpp(2 of 4)

27 // remove 10 from v 28 newLastElement = std::remove( v.begin(), v.end(), 10 );29 30 cout << "\nVector v after removing all 10s:\n ";31 std::copy( v.begin(), newLastElement, output );32 33 std::vector< int > v2( a, a + SIZE );34 std::vector< int > c( SIZE, 0 );35 36 cout << "\n\nVector v2 before removing all 10s "37 << "and copying:\n ";38 std::copy( v2.begin(), v2.end(), output );39 40 // copy from v2 to c, removing 10s in the process 41 std::remove_copy( v2.begin(), v2.end(), c.begin(), 10 );42 43 cout << "\nVector c after removing all 10s from v2:\n ";44 std::copy( c.begin(), c.end(), output );45 46 std::vector< int > v3( a, a + SIZE );47 48 cout << "\n\nVector v3 before removing all elements"49 << "\ngreater than 9:\n ";50 std::copy( v3.begin(), v3.end(), output );51

Remove all 10's from v. Returns an iterator pointing to the new last element.

Use remove_copy to create a duplicate of v, with all the 10's removed.

Page 91: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_28.cpp(3 of 4)

52 // remove elements greater than 9 from v3 53 newLastElement = 54 std::remove_if( v3.begin(), v3.end(), greater9 );55 56 cout << "\nVector v3 after removing all elements"57 << "\ngreater than 9:\n ";58 std::copy( v3.begin(), newLastElement, output );59 60 std::vector< int > v4( a, a + SIZE );61 std::vector< int > c2( SIZE, 0 );62 63 cout << "\n\nVector v4 before removing all elements"64 << "\ngreater than 9 and copying:\n ";65 std::copy( v4.begin(), v4.end(), output );66 67 // copy elements from v4 to c2, removing elements greater68 // than 9 in the process 69 std::remove_copy_if( 70 v4.begin(), v4.end(), c2.begin(), greater9 ); 71 72 cout << "\nVector c2 after removing all elements"73 << "\ngreater than 9 from v4:\n ";74 std::copy( c2.begin(), c2.end(), output );75

Use function greater9 to determine whether to remove the element.

Note use of remove_copy_if.

Page 92: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_28.cpp(4 of 4)

76 cout << endl;77 78 return 0;79 80 } // end main81 82 // determine whether argument is greater than 983 bool greater9( int x )84 {85 return x > 9;86 87 } // end greater9

Page 93: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_28.cppoutput (1 of 1)

Vector v before removing all 10s: 10 2 10 4 16 6 14 8 12 10Vector 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 10Vector c after removing all 10s from v2: 2 4 16 6 14 8 12 0 0 0 Vector v3 before removing all elementsgreater than 9: 10 2 10 4 16 6 14 8 12 10Vector v3 after removing all elementsgreater than 9: 2 4 6 8 Vector v4 before removing all elementsgreater than 9 and copying: 10 2 10 4 16 6 14 8 12 10Vector c2 after removing all elementsgreater than 9 from v4: 2 4 6 8 0 0 0 0 0 0

Page 94: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 95: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_29.cpp(1 of 4)

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

Page 96: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_29.cpp(2 of 4)

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

Use functions replace, replace_copy.

Page 97: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_29.cpp(3 of 4)

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

Page 98: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_29.cpp(4 of 4)

fig21_29.cppoutput (1 of 1)

78 79 // determine whether argument is greater than 980 bool greater9( int x )81 {82 return x > 9;83 84 } // end function greater9

Vector v1 before replacing all 10s: 10 2 10 4 16 6 14 8 12 10Vector 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 10Vector 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 10Vector v3 after replacing all values greaterthan 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 10Vector c2 after replacing all values greater than 9 in v4: 100 2 100 4 100 6 100 8 100 100

Page 99: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 100: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 101: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_30.cpp(1 of 5)

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

Page 102: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_30.cpp(2 of 5)

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

Page 103: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_30.cpp(3 of 5)

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

Page 104: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_30.cpp(4 of 5)

72 73 cout << "\n\nThe cube of every integer in Vector v is:\n";74 std::copy( cubes.begin(), cubes.end(), output );75 76 cout << endl;77 78 return 0;79 80 } // end main81 82 // determine whether argument is greater than 983 bool greater9( int value ) 84 { 85 return value > 9; 86 87 } // end function greater988 89 // output square of argument90 void outputSquare( int value ) 91 { 92 cout << value * value << ' '; 93 94 } // end function outputSquare95

Page 105: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_30.cpp(5 of 5)

fig21_30.cppoutput (1 of 1)

96 // return cube of argument97 int calculateCube( int value ) 98 { 99 return value * value * value; 100 101 } // end function calculateCube

Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10Vector 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 10Number of elements matching 8: 3Number of elements greater than 9: 3 Minimum element in Vector v2 is: 1Maximum element in Vector v2 is: 100 The total of the elements in Vector v is: 55 The square of every integer in Vector v is:25 16 1 9 49 64 81 100 36 4 The cube of every integer in Vector v is:125 64 1 27 343 512 729 1000 216 8

Page 106: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 107: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_31.cpp(1 of 4)

1 // Fig. 21.31: fig21_31.cpp2 // Standard library search and sort algorithms.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <algorithm> // algorithm definitions9 #include <vector> // vector class-template definition10 11 bool greater10( int value ); // prototype12 13 int main()14 {15 const int SIZE = 10;16 int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 };17 18 std::vector< int > v( a, a + SIZE );19 std::ostream_iterator< int > output( cout, " " );20 21 cout << "Vector v contains: ";22 std::copy( v.begin(), v.end(), output );23 24 // locate first occurrence of 16 in v 25 std::vector< int >::iterator location; 26 location = std::find( v.begin(), v.end(), 16 );

Page 108: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_31.cpp(2 of 4)

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

Page 109: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_31.cpp(3 of 4)

53 // sort elements of v54 std::sort( v.begin(), v.end() );55 56 cout << "\n\nVector v after sort: ";57 std::copy( v.begin(), v.end(), output );58 59 // use binary_search to locate 13 in v60 if ( std::binary_search( v.begin(), v.end(), 13 ) )61 cout << "\n\n13 was found in v";62 else63 cout << "\n\n13 was not found in v";64 65 // use binary_search to locate 100 in v66 if ( std::binary_search( v.begin(), v.end(), 100 ) )67 cout << "\n100 was found in v";68 else69 cout << "\n100 was not found in v";70 71 cout << endl;72 73 return 0;74 75 } // end main76

Page 110: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_31.cpp(4 of 4)

fig21_31.cppoutput (1 of 1)

77 // determine whether argument is greater than 1078 bool greater10( int value ) 79 { 80 return value > 10; 81 82 } // end function greater10

Vector v contains: 10 2 17 5 16 8 13 11 20 7 Found 16 at location 4100 not found The first value greater than 10 is 17found at location 2 Vector v after sort: 2 5 7 8 10 11 13 16 17 20 13 was found in v100 was not found in v

Page 111: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 112: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_32.cpp(1 of 2)

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

Page 113: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_32.cpp(2 of 2)

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

Page 114: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_32.cppoutput (1 of 1)

Array a contains: 1 2 3 4 5 6 7 8 9 10Array a after swapping a[0] and a[1] using swap: 2 1 3 4 5 6 7 8 9 10Array a after swapping a[0] and a[1] using iter_swap: 1 2 3 4 5 6 7 8 9 10Array a after swapping the first five elementswith the last five elements: 6 7 8 9 10 1 2 3 4 5

Page 115: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 116: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_33.cpp(1 of 3)

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

Page 117: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_33.cpp(2 of 3)

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

Page 118: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_33.cpp(3 of 3)

fig21_33.cppoutput (1 of 1)

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

Vector v1 contains: 1 3 5 7 9Vector v2 contains: 2 4 5 7 9 After copy_backward, results contains: 1 3 5 7 9 After merge of v1 and v2 results2 contains:1 2 3 4 5 5 7 7 9 9 After unique results2 contains:1 2 3 4 5 7 9 Vector v1 after reverse: 9 7 5 3 1

Page 119: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 120: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_34.cpp(1 of 2)

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

Page 121: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_34.cpp(2 of 2)

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

Page 122: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_34.cppoutput (1 of 1)

Vector v1 contains: 1 3 5 7 9 1 3 5 7 9After inplace_merge, v1 contains: 1 1 3 3 5 5 7 7 9 9After unique_copy results1 contains: 1 3 5 7 9After reverse_copy, results2 contains: 9 9 7 7 5 5 3 3 1 1

Page 123: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 124: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 125: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_35.cpp(1 of 3)

1 // Fig. 21.35: fig21_35.cpp2 // Standard library algorithms includes, set_difference, 3 // set_intersection, set_symmetric_difference and set_union.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <algorithm> // algorithm definitions10 11 int main()12 {13 const int SIZE1 = 10, SIZE2 = 5, SIZE3 = 20;14 int a1[ SIZE1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };15 int a2[ SIZE2 ] = { 4, 5, 6, 7, 8 };16 int a3[ SIZE2 ] = { 4, 5, 6, 11, 15 };17 std::ostream_iterator< int > output( cout, " " );18 19 cout << "a1 contains: ";20 std::copy( a1, a1 + SIZE1, output );21 cout << "\na2 contains: ";22 std::copy( a2, a2 + SIZE2, output );23 cout << "\na3 contains: ";24 std::copy( a3, a3 + SIZE2, output );25

Page 126: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_35.cpp(2 of 3)

26 // determine whether set a2 is completely contained in a127 if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) )28 cout << "\n\na1 includes a2";29 else30 cout << "\n\na1 does not include a2";31 32 // determine whether set a3 is completely contained in a133 if ( std::includes( a1, a1 + SIZE1, a3, a3 + SIZE2 ) )34 cout << "\na1 includes a3";35 else36 cout << "\na1 does not include a3";37 38 int difference[ SIZE1 ];39 40 // determine elements of a1 not in a2 41 int *ptr = std::set_difference( a1, a1 + SIZE1,42 a2, a2 + SIZE2, difference ); 43 44 cout << "\n\nset_difference of a1 and a2 is: ";45 std::copy( difference, ptr, output );46 47 int intersection[ SIZE1 ];48 49 // determine elements in both a1 and a2 50 ptr = std::set_intersection( a1, a1 + SIZE1,51 a2, a2 + SIZE2, intersection ); 52

Page 127: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_35.cpp(3 of 3)

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

Page 128: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_35.cppoutput (1 of 1)

a1 contains: 1 2 3 4 5 6 7 8 9 10a2 contains: 4 5 6 7 8a3 contains: 4 5 6 11 15 a1 includes a2a1 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

Page 129: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 130: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_36.cpp(1 of 4)

1 // Fig. 21.36: fig21_36.cpp2 // Standard library functions lower_bound, upper_bound and 3 // equal_range for a sorted sequence of values.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <algorithm> // algorithm definitions10 #include <vector> // vector class-template definition11 12 int main()13 {14 const int SIZE = 10;15 int a1[] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 };16 std::vector< int > v( a1, a1 + SIZE );17 std::ostream_iterator< int > output( cout, " " );18 19 cout << "Vector v contains:\n";20 std::copy( v.begin(), v.end(), output );21 22 // determine lower-bound insertion point for 6 in v23 std::vector< int >::iterator lower; 24 lower = std::lower_bound( v.begin(), v.end(), 6 ); 25

Page 131: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_36.cpp(2 of 4)

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

Page 132: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_36.cpp(3 of 4)

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

Page 133: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_36.cpp(4 of 4)

fig21_36.cppoutput (1 of 1)

78 79 return 0;80 81 } // end main

Vector v contains:2 2 4 4 4 6 6 6 6 8 Lower bound of 6 is element 5 of vector vUpper bound of 6 is element 9 of vector vUsing equal_range: Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Use lower_bound to locate the first pointat which 5 can be inserted in order Lower bound of 5 is element 5 of vector v Use upper_bound to locate the last pointat which 7 can be inserted in order Upper bound of 7 is element 9 of vector v Use equal_range to locate the first andlast point at which 5 can be inserted in order Lower bound of 5 is element 5 of vector v Upper bound of 5 is element 5 of vector v

Page 134: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 135: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 136: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_37.cpp(1 of 3)

1 // Fig. 21.37: fig21_37.cpp2 // Standard library algorithms push_heap, pop_heap, 3 // make_heap and sort_heap.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <algorithm>10 #include <vector>11 12 int main()13 {14 const int SIZE = 10;15 int a[ SIZE ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };16 std::vector< int > v( a, a + SIZE ), v2;17 std::ostream_iterator< int > output( cout, " " );18 19 cout << "Vector v before make_heap:\n";20 std::copy( v.begin(), v.end(), output );21 22 // create heap from vector v 23 std::make_heap( v.begin(), v.end() );24 25 cout << "\nVector v after make_heap:\n";26 std::copy( v.begin(), v.end(), output );

Create a new heap.

Page 137: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_37.cpp(2 of 3)

27 28 // sort elements of v with sort_heap 29 std::sort_heap( v.begin(), v.end() );30 31 cout << "\nVector v after sort_heap:\n";32 std::copy( v.begin(), v.end(), output );33 34 // perform the heapsort with push_heap and pop_heap35 cout << "\n\nArray a contains: ";36 std::copy( a, a + SIZE, output );37 38 cout << endl;39 40 // place elements of array a into v2 and 41 // maintain elements of v2 in heap42 for ( int i = 0; i < SIZE; ++i ) {43 v2.push_back( a[ i ] );44 std::push_heap( v2.begin(), v2.end() ); 45 cout << "\nv2 after push_heap(a[" << i << "]): ";46 std::copy( v2.begin(), v2.end(), output );47 48 } // end for49 50 cout << endl;51

Add elements one at a time.

Page 138: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_37.cpp(3 of 3)

52 // remove elements from heap in sorted order53 for ( int j = 0; j < v2.size(); ++j ) {54 cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";55 std::pop_heap( v2.begin(), v2.end() - j );56 std::copy( v2.begin(), v2.end(), output );57 58 } // end for59 60 cout << endl;61 62 return 0;63 64 } // end main

Page 139: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_37.cppoutput (1 of 2)

Vector v before make_heap:3 100 52 77 22 31 1 98 13 40Vector v after make_heap:100 98 52 77 40 31 1 3 13 22Vector v after sort_heap:1 3 13 22 31 40 52 77 98 100 Array a contains: 3 100 52 77 22 31 1 98 13 40 v2 after push_heap(a[0]): 3v2 after push_heap(a[1]): 100 3v2 after push_heap(a[2]): 100 3 52v2 after push_heap(a[3]): 100 77 52 3v2 after push_heap(a[4]): 100 77 52 3 22v2 after push_heap(a[5]): 100 77 52 3 22 31v2 after push_heap(a[6]): 100 77 52 3 22 31 1v2 after push_heap(a[7]): 100 98 52 77 22 31 1 3v2 after push_heap(a[8]): 100 98 52 77 22 31 1 3 13v2 after push_heap(a[9]): 100 98 52 77 40 31 1 3 13 22

Page 140: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_37.cppoutput (2 of 2)

v2 after 100 popped from heap98 77 52 22 40 31 1 3 13 100v2 after 98 popped from heap77 40 52 22 13 31 1 3 98 100v2 after 77 popped from heap52 40 31 22 13 3 1 77 98 100v2 after 52 popped from heap40 22 31 1 13 3 52 77 98 100v2 after 40 popped from heap31 22 3 1 13 40 52 77 98 100v2 after 31 popped from heap22 13 3 1 31 40 52 77 98 100v2 after 22 popped from heap13 1 3 22 31 40 52 77 98 100v2 after 13 popped from heap3 1 13 22 31 40 52 77 98 100v2 after 3 popped from heap1 3 13 22 31 40 52 77 98 100v2 after 1 popped from heap1 3 13 22 31 40 52 77 98 100

Page 141: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

21.5.13 min and max

• min(value1, value2)– Returns smaller element

• max(value1, value2)– Returns larger element

Page 142: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_38.cpp(1 of 1)

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

Page 143: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_38.cppoutput (1 of 1)

The minimum of 12 and 7 is: 7The maximum of 12 and 7 is: 12The minimum of 'G' and 'Z' is: GThe maximum of 'G' and 'Z' is: Z

Page 144: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 145: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 146: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

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

Page 147: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_40.cpp(1 of 3)

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

Page 148: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_40.cpp(2 of 3)

24 // perform Sieve of Eratosthenes25 int finalBit = sqrt( sieve.size() ) + 1;26 27 for ( int i = 2; i < finalBit; ++i ) 28 29 if ( sieve.test( i ) ) 30 31 for ( int j = 2 * i; j < size; j += i ) 32 sieve.reset( j );33 34 cout << "The prime numbers in the range 2 to 1023 are:\n";35 36 // display prime numbers in range 2-102337 for ( int k = 2, counter = 0; k < size; ++k )38 39 if ( sieve.test( k ) ) {40 cout << setw( 5 ) << k;41 42 if ( ++counter % 12 == 0 ) 43 cout << '\n';44 45 } // end outer if 46 47 cout << endl;48

Sieve of Eratosthenes: turn off bits for all multiples of a number. What bits remain are prime.

Page 149: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_40.cpp(3 of 3)

49 // get value from user to determine whether value is prime50 cout << "\nEnter a value from 1 to 1023 (-1 to end): ";51 cin >> value;52 53 while ( value != -1 ) {54 55 if ( sieve[ value ] )56 cout << value << " is a prime number\n";57 else58 cout << value << " is not a prime number\n";59 60 cout << "\nEnter a value from 2 to 1023 (-1 to end): ";61 cin >> value;62 63 } // end while64 65 return 0;66 67 } // end main

Page 150: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_40.cppoutput (1 of 1)

The prime numbers in the range 2 to 1023 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 Enter a value from 1 to 1023 (-1 to end): 389389 is a prime number Enter a value from 2 to 1023 (-1 to end): 8888 is not a prime number Enter a value from 2 to 1023 (-1 to end): -1

Page 151: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

21.7 Function Objects

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

STL function objects Type 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

Page 152: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_42.cpp(1 of 4)

1 // Fig. 21.42: fig21_42.cpp2 // Demonstrating function objects.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <vector> // vector class-template definition9 #include <algorithm> // copy algorithm10 #include <numeric> // accumulate algorithm11 #include <functional> // binary_function definition12 13 // binary function adds square of its second argument and14 // running total in its first argument, then returns sum 15 int sumSquares( int total, int value ) 16 { 17 return total + value * value; 18 19 } // end function sumSquares 20

Create a function to be used with accumulate.

Page 153: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_42.cpp(2 of 4)

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 29 // add square of value to total and return result 30 const T operator()( const T &total, const T &value ) 31 { 32 return total + value * value; 33 34 } // end function operator() 35 36 }; // end class SumSquaresClass 37

Create a function object (it can also encapsulate data). Overload operator().

Page 154: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_42.cpp(3 of 4)

38 int main()39 {40 const int SIZE = 10;41 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };42 43 std::vector< int > integers( array, array + SIZE );44 45 std::ostream_iterator< int > output( cout, " " );46 47 int result = 0;48 49 cout << "vector v contains:\n";50 std::copy( integers.begin(), integers.end(), output );51 52 // calculate sum of squares of elements of vector integers 53 // using binary function sumSquares 54 result = std::accumulate( integers.begin(), integers.end(),55 0, sumSquares ); 56 57 cout << "\n\nSum of squares of elements in integers using "58 << "binary\nfunction sumSquares: " << result;59

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.

Page 155: Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction

fig21_42.cpp(4 of 4)

fig21_42.cppoutput (1 of 1)

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

vector v contains:1 2 3 4 5 6 7 8 9 10 Sum of squares of elements in integers using binaryfunction sumSquares: 385 Sum of squares of elements in integers using binaryfunction object of type SumSquaresClass< int >: 385

Use accumulate with a function object.