Chapter 21 - Standard Template Library (STL)

Slides:



Advertisements
Similar presentations
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 20 - Standard Template Library (STL) Outline 20.1Introduction to the Standard Template Library.
Advertisements

. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
More on the STL vector list stack queue priority_queue.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to the Standard Template Library (STL) STL –Useful template-based components Containers:
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 - Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Writing Your Own STL Container Ray Lischner
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
 2003 Prentice Hall, Inc. All rights reserved stack Adapter stack –Header –Insertions and deletions at one end –Last-in, first-out (LIFO) data.
Data Structures Using C++ 2E
Containers Overview and Class Vector
1 CSC 262 Programming in C++ II Sykes Day 18.  We’ve repeatedly emphasized the importance of software reuse.  Recognizing that many data structures.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
C++ STL CSCI 3110.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
Generic Programming and the STL Andreas Fabri GeometryFactory.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
 2003 Prentice Hall, Inc. All rights reserved Introduction to the Standard Template Library (STL) STL –Powerful, template-based components Containers:
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools File Processing, Standard Template Library Lecture 12 July.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
The Standard Template Library Container Classes Version 1.0.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Standard Template Library Lecture 9 March 22, 2005.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Standard Template Library Lecture 12 April 6, 2004.
Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) Introduction to Containers Introduction.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
 2003 Prentice Hall, Inc. All rights reserved vector Sequence Container Declarations –std::vector v; type : int, float, etc. Iterators –std::vector.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 - Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Object-Oriented Programming (OOP) Lecture No. 42.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Object-Oriented Programming (OOP) Lecture No. 41
Standard Template Library
CS212: Object Oriented Analysis and Design
Standard Template Library
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
Chapter 20 - Standard Template Library (STL)
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
priority_queue<T>
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 21 - Standard Template Library (STL)
Class string and String Stream Processing
Chapter 21 - Standard Template Library (STL)
Chapter 21 - Standard Template Library (STL)
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Lecture 8 : Intro. to STL (Standard Template Library)
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Standard Template Library
Standard Template Library
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 3 Lists, Stacks, and Queues
Standard Template Library
Chapter 21 - Standard Template Library (STL)
Presentation transcript:

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

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

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

21.1.1 Introduction to Containers Three types of containers Sequence containers Linear data structures (vectors, linked lists) First-class container Associative containers Non-linear, can find elements quickly Key/value pairs Container adapters Near containers Similar to containers, with reduced functionality Containers have some common functions

STL Container Classes (Fig. 21.1) Sequence containers vector deque list Associative containers set multiset map multimap Container adapters stack queue priority_queue

Common STL Member Functions (Fig. 21.2) Member functions for all containers Default constructor, copy constructor, destructor empty max_size, size = < <= > >= == != swap Functions for first-class containers begin, end rbegin, rend erase, clear

Common STL typedefs (Fig. 21.4) typedefs for first-class containers value_type reference const_reference pointer iterator const_iterator reverse_iterator const_reverse_iterator difference_type size_type

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

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

Access and assign the iterator like a pointer. 1 // Fig. 21.5: fig21_05.cpp 2 // 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_iterator 10 11 int main() 12 { 13 cout << "Enter two integers: "; 14 15 // create istream_iterator for reading int values from cin 16 std::istream_iterator< int > inputInt( cin ); 17 18 int number1 = *inputInt; // read int from standard input 19 ++inputInt; // move iterator to next input value 20 int number2 = *inputInt; // read int from standard input 21 fig21_05.cpp (1 of 2) Note creation of istream_iterator. For compilation reasons, we use std:: rather than a using statement. Access and assign the iterator like a pointer.

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

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

Iterator Types Supported (Fig. 21.8) Sequence containers vector: random access deque: random access list: bidirectional Associative containers (all bidirectional) set multiset Map multimap Container adapters (no iterators supported) stack queue priority_queue

Iterator Operations (Fig. 21.10) All ++p, p++ Input iterators *p p = p1 p == p1, p != p1 Output iterators Forward iterators Have functionality of input and output iterators

Iterator Operations (Fig. 21.10) Bidirectional --p, p-- Random access p + i, p += i p - i, p -= i p[i] p < p1, p <= p1 p > p1, p >= p1

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

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

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

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

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

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

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

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

fig21_14.cpp (1 of 3) Create a vector of ints. Call member functions. 1 // Fig. 21.14: fig21_14.cpp 2 // 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 definition 10 11 // prototype for function template printVector 12 template < class T > 13 void printVector( const std::vector< T > &integers2 ); 14 15 int main() 16 { 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 fig21_14.cpp (1 of 3) Create a vector of ints. Call member functions.

Add elements to end of vector using push_back. 27 // function push_back is in every sequence collection 28 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. fig21_14.cpp (2 of 3)

Walk through vector backwards using a reverse_iterator. 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 main 58 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. fig21_14.cpp (3 of 3) Template function to walk through vector forwards.

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

Create vector (initialized using an array) and ostream_iterator. 1 // Fig. 21.15: fig21_15.cpp 2 // 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 definition 10 #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 fig21_15.cpp (1 of 3) Create vector (initialized using an array) and ostream_iterator. Copy range of iterators to output (ostream_iterator).

More vector member functions. 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 10 28 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 element 36 try { 37 integers.at( 100 ) = 777; 38 39 } // end try 40 41 // catch out_of_range exception 42 catch ( std::out_of_range outOfRange ) { 43 cout << "\n\nException: " << outOfRange.what(); 44 45 } // end catch 46 47 // erase first element 48 integers.erase( integers.begin() ); 49 cout << "\n\nVector integers after erasing first element: "; 50 std::copy( integers.begin(), integers.end(), output ); 51 More vector member functions. fig21_15.cpp (2 of 3) at has range checking, and can throw an exception.

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 array 58 integers.insert( integers.begin(), array, array + SIZE ); 59 cout << "\n\nContents of vector integers before clear: "; 60 std::copy( integers.begin(), integers.end(), output ); 61 62 // empty integers; clear calls erase to empty a collection 63 integers.clear(); 64 cout << "\nAfter clear, vector integers " 65 << ( integers.empty() ? "is" : "is not" ) << " empty"; 66 67 cout << endl; 68 69 return 0; 70 71 } // end main fig21_15.cpp (3 of 3)

fig21_15.cpp output (1 of 1) Vector integers contains: 1 2 3 4 5 6 First element of integers: 1 Last element of integers: 6   Contents of vector integers after changes: 7 22 2 10 4 5 6 Exception: invalid vector<T> subscript Vector integers after erasing first element: 22 2 10 4 5 6 After erasing all elements, vector integers is empty Contents of vector integers before clear: 1 2 3 4 5 6 After clear, vector integers is empty fig21_15.cpp output (1 of 1)

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

21.2.2 list Sequence Container list functions for object t t.sort() Sorts in ascending order t.splice(iterator, otherObject ); Inserts values from otherObject before iterator t.merge( otherObject ) Removes otherObject and inserts it into t, sorted t.unique() Removes duplicate elements

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

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

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

fig21_17.cpp (3 of 5) 55 // insert elements of array into otherValues 56 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 values 64 // in sorted order 65 values.merge( otherValues ); 66 67 cout << "\nAfter merge:\n values contains: "; 68 printList( values ); 69 cout << "\n otherValues contains: "; 70 printList( otherValues ); 71 72 values.pop_front(); // remove element from front 73 values.pop_back(); // remove element from back 74 75 cout << "\nAfter pop_front and pop_back:" 76 << "\n values contains: "; 77 printList( values ); 78 79 values.unique(); // remove duplicate elements 80 81 cout << "\nAfter unique, values contains: "; 82 printList( values ); fig21_17.cpp (3 of 5)

fig21_17.cpp (4 of 5) 83 84 // swap elements of values and otherValues 85 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 otherValues 93 values.assign( otherValues.begin(), otherValues.end() ); 94 95 cout << "\nAfter assign, values contains: "; 96 printList( values ); 97 98 // remove otherValues elements and insert into values 99 // in sorted order 100 values.merge( otherValues ); 101 102 cout << "\nAfter merge, values contains: "; 103 printList( values ); 104 105 values.remove( 4 ); // remove all 4s 106 107 cout << "\nAfter remove( 4 ), values contains: "; 108 printList( values ); fig21_17.cpp (4 of 5)

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

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

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

Create a deque, use member functions. 1 // Fig. 21.18: fig21_18.cpp 2 // 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 definition 9 #include <algorithm> // copy algorithm 10 11 int main() 12 { 13 std::deque< double > values; 14 std::ostream_iterator< double > output( cout, " " ); 15 16 // insert elements in values 17 values.push_front( 2.2 ); 18 values.push_front( 3.5 ); 19 values.push_back( 1.1 ); 20 21 cout << "values contains: "; 22 23 // use subscript operator to obtain elements of values 24 for ( int i = 0; i < values.size(); ++i ) 25 cout << values[ i ] << ' '; 26 fig21_18.cpp (1 of 2) Create a deque, use member functions.

fig21_18.cpp (2 of 2) fig21_18.cpp output (1 of 1) 27 values.pop_front(); // remove first element 28 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 1 33 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 fig21_18.cpp (2 of 2) fig21_18.cpp output (1 of 1) values contains: 3.5 2.2 1.1 After pop_front, values contains: 2.2 1.1 After values[ 1 ] = 5.4, values contains: 2.2 5.4

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

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

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

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

1 // Fig. 21.19: fig21_19.cpp 2 // Testing Standard Library class multiset 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <set> // multiset class-template definition 9 10 // define short name for multiset type used in this program 11 typedef std::multiset< int, std::less< int > > ims; 12 13 #include <algorithm> // copy algorithm 14 15 int main() 16 { 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 fig21_19.cpp (1 of 3) typedefs help clarify program. This declares an integer multiset that stores values in ascending order.

Use member function find. 26 intMultiset.insert( 15 ); // insert 15 in intMultiset 27 intMultiset.insert( 15 ); // insert 15 in intMultiset 28 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 values 34 ims::const_iterator result; 35 36 // find 15 in intMultiset; find returns iterator 37 result = intMultiset.find( 15 ); 38 39 if ( result != intMultiset.end() ) // if iterator not at end 40 cout << "Found value 15\n"; // found search value 15 41 42 // find 20 in intMultiset; find returns iterator 43 result = intMultiset.find( 20 ); 44 45 if ( result == intMultiset.end() ) // will be true hence 46 cout << "Did not find value 20\n"; // did not find 20 47 48 // insert elements of array a into intMultiset 49 intMultiset.insert( a, a + SIZE ); 50 51 cout << "\nAfter insert, intMultiset contains:\n"; 52 std::copy( intMultiset.begin(), intMultiset.end(), output ); 53 fig21_19.cpp (2 of 3) Use member function find.

Use a pair object to get the lower and upper bound for 22. 54 // determine lower and upper bound of 22 in intMultiset 55 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 bound 64 // 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 fig21_19.cpp (3 of 3) Use a pair object to get the lower and upper bound for 22.

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

21.3.2 set Associative Container 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;

Create set. Syntax similar to multiset. 1 // Fig. 21.20: fig21_20.cpp 2 // 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 program 11 typedef std::set< double, std::less< double > > double_set; 12 13 #include <algorithm> 14 15 int main() 16 { 17 const int SIZE = 5; 18 double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; 19 20 double_set doubleSet( a, a + SIZE ); 21 std::ostream_iterator< double > output( cout, " " ); 22 23 cout << "doubleSet contains: "; 24 std::copy( doubleSet.begin(), doubleSet.end(), output ); 25 fig21_20.cpp (1 of 3) Create set. Syntax similar to multiset.

26 // p represents pair containing const_iterator and bool 27 std::pair< double_set::const_iterator, bool > p; 28 29 // insert 13.8 in doubleSet; insert returns pair in which 30 // 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 set 42 43 cout << "\n\n" << *( p.first ) 44 << ( p.second ? " was" : " was not" ) << " inserted"; 45 fig21_20.cpp (2 of 3) pair object has a bool value representing whether or not the item was inserted.

fig21_20.cpp (3 of 3) fig21_20.cpp output (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 fig21_20.cpp (3 of 3) fig21_20.cpp output (1 of 1) doubleSet contains: 2.1 3.7 4.2 9.5   13.8 was inserted doubleSet contains: 2.1 3.7 4.2 9.5 13.8 9.5 was not inserted

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

21.3.3 multimap Associative Container Example std::multimap< int, double, std::less< int > > mmapObject; Key type int Value type double Sorted in ascending order Use typedef to simplify code typedef std::multimap<int, double, std::less<int>> mmid; mmid mmapObject; mmapObject.insert( mmid::value_type( 1, 3.4 ) ); Inserts key 1 with value 3.4 mmid::value_type creates a pair object

Definition for a multimap that maps integer keys to double values. 1 // Fig. 21.21: fig21_21.cpp 2 // 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 definition 9 10 // define short name for multimap type used in this program 11 typedef std::multimap< int, double, std::less< int > > mmid; 12 13 int main() 14 { 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"; fig21_21.cpp (1 of 2) Definition for a multimap that maps integer keys to double values. Create multimap and insert key-value pairs.

Use iterator to print entire multimap. 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 pairs 38 for ( mmid::const_iterator iter = pairs.begin(); 39 iter != pairs.end(); ++iter ) 40 cout << iter->first << '\t' 41 << iter->second << '\n'; 42 43 cout << endl; 44 45 return 0; 46 47 } // end main fig21_21.cpp (2 of 2) Use iterator to print entire multimap.

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

21.3.4 map Associative Container 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 > >;

Again, use typedefs to simplify declaration. 1 // Fig. 21.22: fig21_22.cpp 2 // 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 definition 9 10 // define short name for map type used in this program 11 typedef std::map< int, double, std::less< int > > mid; 12 13 int main() 14 { 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 ignored 24 pairs.insert( mid::value_type( 20, 9.345 ) ); 25 pairs.insert( mid::value_type( 15, 99.3 ) ); // dupe ignored 26 fig21_22.cpp (1 of 2) Again, use typedefs to simplify declaration. Duplicate keys ignored.

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

fig21_22.cpp output (1 of 1) pairs contains: Key Value 5 1010.1 5 1010.1 10 22.22 15 2.7 20 9.345 25 33.333 30 111.11   After subscript operations, pairs contains: 25 9999.99 40 8765.43 fig21_22.cpp output (1 of 1)

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

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

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

Use member function push. 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 for 34 35 // display and remove elements from each stack 36 cout << "Popping from intDequeStack: "; 37 popElements( intDequeStack ); 38 cout << "\nPopping from intVectorStack: "; 39 popElements( intVectorStack ); 40 cout << "\nPopping from intListStack: "; 41 popElements( intListStack ); 42 43 cout << endl; 44 45 return 0; 46 47 } // end main 48 Use member function push. fig21_23.cpp (2 of 3)

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

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

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

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

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

fig21_25.cpp (1 of 2) Create priority queue. 1 // Fig. 21.25: fig21_25.cpp 2 // 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 definition 9 10 int main() 11 { 12 std::priority_queue< double > priorities; 13 14 // push elements onto priorities 15 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 element 24 25 } // end while 26 fig21_25.cpp (1 of 2) Create priority queue. Insert items using push. When using pop, highest priority (largest) items removed first.

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

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

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

Create vector of chars, to be used with various functions. 1 // Fig. 21.26: fig21_26.cpp 2 // Standard library algorithms fill, fill_n, generate 3 // and generate_n. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 #include <algorithm> // algorithm definitions 10 #include <vector> // vector class-template definition 11 12 char nextLetter(); // prototype 13 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 fig21_26.cpp (1 of 3) Create vector of chars, to be used with various functions. Function fill.

Functions generate and generate_n use function nextLetter. 25 // fill first five elements of chars with As 26 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 nextLetter 33 std::generate( chars.begin(), chars.end(), nextLetter ); 34 35 cout << "\n\nVector chars after generating letters A-J:\n"; 36 std::copy( chars.begin(), chars.end(), output ); 37 38 // generate values for first five elements of chars 39 // with nextLetter 40 std::generate_n( chars.begin(), 5, nextLetter ); 41 42 cout << "\n\nVector chars after generating K-O for the" 43 << " first five elements:\n"; 44 std::copy( chars.begin(), chars.end(), output ); 45 46 cout << endl; 47 48 return 0; 49 50 } // end main fig21_26.cpp (2 of 3) Functions generate and generate_n use function nextLetter.

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

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

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

fig21_27.cpp (1 of 3) 1 // Fig. 21.27: fig21_27.cpp 2 // 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 definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { 14 const int SIZE = 10; 15 int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 16 int a2[ SIZE ] = { 1, 2, 3, 4, 1000, 6, 7, 8, 9, 10 }; 17 18 std::vector< int > v1( a1, a1 + SIZE ); 19 std::vector< int > v2( a1, a1 + SIZE ); 20 std::vector< int > v3( a2, a2 + SIZE ); 21 22 std::ostream_iterator< int > output( cout, " " ); 23 fig21_27.cpp (1 of 3)

Use function equal. Compares all of v1 with v2. 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 iterators 44 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 fig21_27.cpp (2 of 3) Use function equal. Compares all of v1 with v2. Note use of function mismatch.

Use lexicographical_compare. 51 cout << "\nThere is a mismatch between v1 and v3 at " 52 << "location " << ( location.first - v1.begin() ) 53 << "\nwhere v1 contains " << *location.first 54 << " 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 c2 61 result = std::lexicographical_compare( 62 c1, c1 + SIZE, c2, c2 + SIZE ); 63 64 cout << c1 65 << ( result ? " is less than " : 66 " is greater than or equal to " ) 67 << c2 << endl; 68 69 return 0; 70 71 } // end main fig21_27.cpp (3 of 3) Use lexicographical_compare.

fig21_27.cpp output (1 of 1) Vector v1 contains: 1 2 3 4 5 6 7 8 9 10   Vector v1 is equal to vector v2. Vector v1 is not equal to vector v3. There is a mismatch between v1 and v3 at location 4 where v1 contains 5 and v3 contains 1000 HELLO is greater than or equal to BYE BYE fig21_27.cpp output (1 of 1)

21.5.3 remove, remove_if, remove_copy and remove_copy_if remove( iter1, iter2, value); Removes all instances of value in range (iter1-iter2) Moves instances of value towards end Does not change size of container or delete elements Returns iterator to "new" end of container Elements after new iterator are undefined (0) remove_copy Copies one vector to another while removing an element remove_copy(iter1, iter2, iter3, value); Copies elements not equal to value into iter3 (output iterator) Uses range iter1-iter2

21.5.3 remove, remove_if, remove_copy and remove_copy_if Like remove Returns iterator to last element Removes elements that return true for specified function remove_if(iter1,iter2, function); Elements passed to function, which returns a bool remove_copy_if Like remove_copy and remove_if Copies range of elements to iter3, except those for which function returns true remove_copy_if(iter1, iter2, iter3, function);

fig21_28.cpp (1 of 4) 1 // Fig. 21.28: fig21_28.cpp 2 // 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 definitions 10 #include <vector> // vector class-template definition 11 12 bool greater9( int ); // prototype 13 14 int main() 15 { 16 const int SIZE = 10; 17 int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; 18 19 std::ostream_iterator< int > output( cout, " " ); 20 21 std::vector< int > v( a, a + SIZE ); 22 std::vector< int >::iterator newLastElement; 23 24 cout << "Vector v before removing all 10s:\n "; 25 std::copy( v.begin(), v.end(), output ); 26 fig21_28.cpp (1 of 4)

Use remove_copy to create a duplicate of v, with all the 10's removed. 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. fig21_28.cpp (2 of 4) Use remove_copy to create a duplicate of v, with all the 10's removed.

Use function greater9 to determine whether to remove the element. 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 greater 68 // than 9 in the process 69 std::remove_copy_if( 70 v4.begin(), v4.end(), c2.begin(), greater9 ); 71 72 cout << "\nVector c2 after removing all elements" 73 << "\ngreater than 9 from v4:\n "; 74 std::copy( c2.begin(), c2.end(), output ); 75 Use function greater9 to determine whether to remove the element. fig21_28.cpp (3 of 4) Note use of remove_copy_if.

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

fig21_28.cpp output (1 of 1) Vector v before removing all 10s: 10 2 10 4 16 6 14 8 12 10 Vector v after removing all 10s: 2 4 16 6 14 8 12   Vector v2 before removing all 10s and copying: Vector c after removing all 10s from v2: 2 4 16 6 14 8 12 0 0 0 Vector v3 before removing all elements greater than 9: Vector v3 after removing all elements 2 4 6 8 Vector v4 before removing all elements greater than 9 and copying: Vector c2 after removing all elements greater than 9 from v4: 2 4 6 8 0 0 0 0 0 0 fig21_28.cpp output (1 of 1)

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

fig21_29.cpp (1 of 4) 1 // Fig. 21.29: fig21_29.cpp 2 // 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 fig21_29.cpp (1 of 4)

Use functions replace, replace_copy. 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. fig21_29.cpp (2 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 100 66 std::replace_copy_if( 67 v4.begin(), v4.end(), c2.begin(), greater9, 100 ); 68 69 cout << "\nVector c2 after replacing all values greater " 70 << "than 9 in v4:\n "; 71 std::copy( c2.begin(), c2.end(), output ); 72 73 cout << endl; 74 75 return 0; 76 77 } // end main fig21_29.cpp (3 of 4)

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

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

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

fig21_30.cpp (1 of 5) 1 // Fig. 21.30: fig21_30.cpp 2 // 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 here 10 #include <vector> 11 12 bool greater9( int ); 13 void outputSquare( int ); 14 int calculateCube( int ); 15 16 int main() 17 { 18 const int SIZE = 10; 19 int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 20 21 std::vector< int > v( a1, a1 + SIZE ); 22 std::ostream_iterator< int > output( cout, " " ); 23 24 cout << "Vector v before random_shuffle: "; 25 std::copy( v.begin(), v.end(), output ); 26 fig21_30.cpp (1 of 5)

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 9 45 result = std::count_if( v2.begin(), v2.end(), greater9 ); 46 47 cout << "\nNumber of elements greater than 9: " << result; 48 fig21_30.cpp (2 of 5)

fig21_30.cpp (3 of 5) 49 // locate minimum element in v2 50 cout << "\n\nMinimum element in Vector v2 is: " 51 << *( std::min_element( v2.begin(), v2.end() ) ); 52 53 // locate maximum element in v2 54 cout << "\nMaximum element in Vector v2 is: " 55 << *( std::max_element( v2.begin(), v2.end() ) ); 56 57 // calculate sum of elements in v 58 cout << "\n\nThe total of the elements in Vector v is: " 59 << std::accumulate( v.begin(), v.end(), 0 ); 60 61 cout << "\n\nThe square of every integer in Vector v is:\n"; 62 63 // output square of every element in v 64 std::for_each( v.begin(), v.end(), outputSquare ); 65 66 std::vector< int > cubes( SIZE ); 67 68 // calculate cube of each element in v; 69 // place results in cubes 70 std::transform( 71 v.begin(), v.end(), cubes.begin(), calculateCube ); fig21_30.cpp (3 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 main 81 82 // determine whether argument is greater than 9 83 bool greater9( int value ) 84 { 85 return value > 9; 86 87 } // end function greater9 88 89 // output square of argument 90 void outputSquare( int value ) 91 { 92 cout << value * value << ' '; 93 94 } // end function outputSquare 95 fig21_30.cpp (4 of 5)

fig21_30.cpp (5 of 5) fig21_30.cpp output (1 of 1) 96 // return cube of argument 97 int calculateCube( int value ) 98 { 99 return value * value * value; 100 101 } // end function calculateCube fig21_30.cpp (5 of 5) fig21_30.cpp output (1 of 1) Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10 Vector v after random_shuffle: 5 4 1 3 7 8 9 10 6 2   Vector v2 contains: 100 2 8 1 50 3 8 8 9 10 Number of elements matching 8: 3 Number of elements greater than 9: 3 Minimum element in Vector v2 is: 1 Maximum element in Vector v2 is: 100 The total of the elements in Vector v is: 55 The square of every integer in Vector v is: 25 16 1 9 49 64 81 100 36 4 The cube of every integer in Vector v is: 125 64 1 27 343 512 729 1000 216 8

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

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

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 fig21_31.cpp (2 of 4)

fig21_31.cpp (3 of 4) 53 // sort elements of v 54 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 v 60 if ( std::binary_search( v.begin(), v.end(), 13 ) ) 61 cout << "\n\n13 was found in v"; 62 else 63 cout << "\n\n13 was not found in v"; 64 65 // use binary_search to locate 100 in v 66 if ( std::binary_search( v.begin(), v.end(), 100 ) ) 67 cout << "\n100 was found in v"; 68 else 69 cout << "\n100 was not found in v"; 70 71 cout << endl; 72 73 return 0; 74 75 } // end main 76 fig21_31.cpp (3 of 4)

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

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

fig21_32.cpp (1 of 2) 1 // Fig. 21.32: fig21_32.cpp 2 // 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 definitions 9 10 int main() 11 { 12 const int SIZE = 10; 13 int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 14 std::ostream_iterator< int > output( cout, " " ); 15 16 cout << "Array a contains:\n "; 17 std::copy( a, a + SIZE, output ); 18 19 // swap elements at locations 0 and 1 of array a 20 std::swap( a[ 0 ], a[ 1 ] ); 21 22 cout << "\nArray a after swapping a[0] and a[1] " 23 << "using swap:\n "; 24 std::copy( a, a + SIZE, output ); 25 fig21_32.cpp (1 of 2)

26 // use iterators to swap elements at locations 27 // 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 with 34 // elements in last five elements of array a 35 std::swap_ranges( a, a + 5, a + 5 ); 36 37 cout << "\nArray a after swapping the first five elements\n" 38 << "with the last five elements:\n "; 39 std::copy( a, a + SIZE, output ); 40 41 cout << endl; 42 43 return 0; 44 45 } // end main fig21_32.cpp (2 of 2)

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

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

fig21_33.cpp (1 of 3) 1 // Fig. 21.33: fig21_33.cpp 2 // 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 definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { 14 const int SIZE = 5; 15 int a1[ SIZE ] = { 1, 3, 5, 7, 9 }; 16 int a2[ SIZE ] = { 2, 4, 5, 7, 9 }; 17 18 std::vector< int > v1( a1, a1 + SIZE ); 19 std::vector< int > v2( a2, a2 + SIZE ); 20 21 std::ostream_iterator< int > output( cout, " " ); 22 23 cout << "Vector v1 contains: "; 24 std::copy( v1.begin(), v1.end(), output ); 25 cout << "\nVector v2 contains: "; 26 std::copy( v2.begin(), v2.end(), output ); fig21_33.cpp (1 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 order 39 std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(), 40 results2.begin() ); 41 42 cout << "\n\nAfter merge of v1 and v2 results2 contains:\n"; 43 std::copy( results2.begin(), results2.end(), output ); 44 45 // eliminate duplicate values from results2 46 std::vector< int >::iterator endLocation; 47 endLocation = 48 std::unique( results2.begin(), results2.end() ); 49 50 cout << "\n\nAfter unique results2 contains:\n"; 51 std::copy( results2.begin(), endLocation, output ); 52 fig21_33.cpp (2 of 3)

fig21_33.cpp (3 of 3) fig21_33.cpp output (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 fig21_33.cpp (3 of 3) fig21_33.cpp output (1 of 1) Vector v1 contains: 1 3 5 7 9 Vector v2 contains: 2 4 5 7 9   After copy_backward, results contains: 1 3 5 7 9 After merge of v1 and v2 results2 contains: 1 2 3 4 5 5 7 7 9 9 After unique results2 contains: 1 2 3 4 5 7 9 Vector v1 after reverse: 9 7 5 3 1

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

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

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

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

21.5.10 Set Operations set_symmetric_difference(iter1, iter2, iter3, iter4, iter5) Copies elements in set (1-2) but not set (3-4), and vice versa, into iter5 a1: 1 2 3 4 5 6 7 8 9 10 a2: 4 5 6 7 8 set_symmetric_difference: 1 2 3 9 10 Both sets must be sorted set_union( iter1, iter2, iter3, iter4, iter5) Copies elements in either or both sets to iter5

fig21_35.cpp (1 of 3) 1 // Fig. 21.35: fig21_35.cpp 2 // 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 definitions 10 11 int main() 12 { 13 const int SIZE1 = 10, SIZE2 = 5, SIZE3 = 20; 14 int a1[ SIZE1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 15 int a2[ SIZE2 ] = { 4, 5, 6, 7, 8 }; 16 int a3[ SIZE2 ] = { 4, 5, 6, 11, 15 }; 17 std::ostream_iterator< int > output( cout, " " ); 18 19 cout << "a1 contains: "; 20 std::copy( a1, a1 + SIZE1, output ); 21 cout << "\na2 contains: "; 22 std::copy( a2, a2 + SIZE2, output ); 23 cout << "\na3 contains: "; 24 std::copy( a3, a3 + SIZE2, output ); 25 fig21_35.cpp (1 of 3)

26 // determine whether set a2 is completely contained in a1 27 if ( std::includes( a1, a1 + SIZE1, a2, a2 + SIZE2 ) ) 28 cout << "\n\na1 includes a2"; 29 else 30 cout << "\n\na1 does not include a2"; 31 32 // determine whether set a3 is completely contained in a1 33 if ( std::includes( a1, a1 + SIZE1, a3, a3 + SIZE2 ) ) 34 cout << "\na1 includes a3"; 35 else 36 cout << "\na1 does not include a3"; 37 38 int difference[ SIZE1 ]; 39 40 // determine elements of a1 not in a2 41 int *ptr = std::set_difference( a1, a1 + SIZE1, 42 a2, a2 + SIZE2, difference ); 43 44 cout << "\n\nset_difference of a1 and a2 is: "; 45 std::copy( difference, ptr, output ); 46 47 int intersection[ SIZE1 ]; 48 49 // determine elements in both a1 and a2 50 ptr = std::set_intersection( a1, a1 + SIZE1, 51 a2, a2 + SIZE2, intersection ); 52 fig21_35.cpp (2 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 sets 69 ptr = std::set_union( a1, a1 + SIZE1, 70 a3, a3 + SIZE2, unionSet ); 71 72 cout << "\n\nset_union of a1 and a3 is: "; 73 std::copy( unionSet, ptr, output ); 74 75 cout << endl; 76 77 return 0; 78 79 } // end main fig21_35.cpp (3 of 3)

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

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

fig21_36.cpp (1 of 4) 1 // Fig. 21.36: fig21_36.cpp 2 // 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 definitions 10 #include <vector> // vector class-template definition 11 12 int main() 13 { 14 const int SIZE = 10; 15 int a1[] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 }; 16 std::vector< int > v( a1, a1 + SIZE ); 17 std::ostream_iterator< int > output( cout, " " ); 18 19 cout << "Vector v contains:\n"; 20 std::copy( v.begin(), v.end(), output ); 21 22 // determine lower-bound insertion point for 6 in v 23 std::vector< int >::iterator lower; 24 lower = std::lower_bound( v.begin(), v.end(), 6 ); 25 fig21_36.cpp (1 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 v 30 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- and 37 // upper-bound insertion points for 6 38 std::pair< std::vector< int >::iterator, 39 std::vector< int >::iterator > eq; 40 eq = std::equal_range( v.begin(), v.end(), 6 ); 41 42 cout << "\nUsing equal_range:\n" 43 << " Lower bound of 6 is element " 44 << ( eq.first - v.begin() ) << " of vector v"; 45 cout << "\n Upper bound of 6 is element " 46 << ( eq.second - v.begin() ) << " of vector v"; 47 48 cout << "\n\nUse lower_bound to locate the first point\n" 49 << "at which 5 can be inserted in order"; 50 fig21_36.cpp (2 of 4)

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

fig21_36.cpp (4 of 4) fig21_36.cpp output (1 of 1) 78 79 return 0; 80 81 } // end main fig21_36.cpp (4 of 4) fig21_36.cpp output (1 of 1) Vector v contains: 2 2 4 4 4 6 6 6 6 8   Lower bound of 6 is element 5 of vector v Upper bound of 6 is element 9 of vector v Using equal_range: Use lower_bound to locate the first point at which 5 can be inserted in order Lower bound of 5 is element 5 of vector v Use upper_bound to locate the last point at which 7 can be inserted in order Upper bound of 7 is element 9 of vector v Use equal_range to locate the first and last point at which 5 can be inserted in order Upper bound of 5 is element 5 of vector v

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

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

fig21_37.cpp (1 of 3) Create a new heap. 1 // Fig. 21.37: fig21_37.cpp 2 // 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 ); fig21_37.cpp (1 of 3) Create a new heap.

Add elements one at a time. 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_heap 35 cout << "\n\nArray a contains: "; 36 std::copy( a, a + SIZE, output ); 37 38 cout << endl; 39 40 // place elements of array a into v2 and 41 // maintain elements of v2 in heap 42 for ( int i = 0; i < SIZE; ++i ) { 43 v2.push_back( a[ i ] ); 44 std::push_heap( v2.begin(), v2.end() ); 45 cout << "\nv2 after push_heap(a[" << i << "]): "; 46 std::copy( v2.begin(), v2.end(), output ); 47 48 } // end for 49 50 cout << endl; 51 fig21_37.cpp (2 of 3) Add elements one at a time.

fig21_37.cpp (3 of 3) 52 // remove elements from heap in sorted order 53 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 for 59 60 cout << endl; 61 62 return 0; 63 64 } // end main fig21_37.cpp (3 of 3)

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

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

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

fig21_38.cpp (1 of 1) 1 // Fig. 21.38: fig21_38.cpp 2 // 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 fig21_38.cpp (1 of 1)

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

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

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

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

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 definition 14 #include <cmath> // sqrt prototype 15 16 int main() 17 { 18 const int size = 1024; 19 int value; 20 std::bitset< size > sieve; 21 22 sieve.flip(); 23 fig21_40.cpp (1 of 3)

24 // perform Sieve of Eratosthenes 25 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-1023 37 for ( int k = 2, counter = 0; k < size; ++k ) 38 39 if ( sieve.test( k ) ) { 40 cout << setw( 5 ) << k; 41 42 if ( ++counter % 12 == 0 ) 43 cout << '\n'; 44 45 } // end outer if 46 47 cout << endl; 48 Sieve of Eratosthenes: turn off bits for all multiples of a number. What bits remain are prime. fig21_40.cpp (2 of 3)

49 // get value from user to determine whether value is prime 50 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 else 58 cout << value << " is not a prime number\n"; 59 60 cout << "\nEnter a value from 2 to 1023 (-1 to end): "; 61 cin >> value; 62 63 } // end while 64 65 return 0; 66 67 } // end main fig21_40.cpp (3 of 3)

The prime numbers in the range 2 to 1023 are: 2 3 5 7 11 13 17 19 23 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): 389 389 is a prime number Enter a value from 2 to 1023 (-1 to end): 88 88 is not a prime number Enter a value from 2 to 1023 (-1 to end): -1 fig21_40.cpp output (1 of 1)

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

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

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 fig21_42.cpp (2 of 4) Create a function object (it can also encapsulate data). Overload operator().

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 fig21_42.cpp (3 of 4) accumulate initially passes 0 as the first argument, with the first element as the second. It then uses the return value as the first argument, and iterates through the other elements.

fig21_42.cpp (4 of 4) fig21_42.cpp output (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 fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1) Use accumulate with a function object. vector v contains: 1 2 3 4 5 6 7 8 9 10   Sum of squares of elements in integers using binary function sumSquares: 385 function object of type SumSquaresClass< int >: 385