 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to the Standard Template Library (STL) STL –Useful template-based components Containers:

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

 2000 Deitel & Associates, Inc. All rights reserved. Chapter 20 - Standard Template Library (STL) Outline 20.1Introduction to the Standard Template Library.
. 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.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
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.
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
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.
Templates and the STL.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
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.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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)
Generic Programming and the STL Andreas Fabri GeometryFactory.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
 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.
C++ Review STL CONTAINERS.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
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.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
Chapter 21 - Standard Template Library (STL)
Chapter 21 - Standard Template Library (STL)
Chapter 21 - Standard Template Library (STL)
Iterators and STL Containers
Standard Template Library
Standard Template Library
Chapter 21 - Standard Template Library (STL)
Standard Template Library
Chapter 21 - Standard Template Library (STL)
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to the Standard Template Library (STL) STL –Useful 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

 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction to Containers Three types of containers –Sequence containers Linear data structures (vectors, linked lists) –Associative containers Non-linear, can find elements quickly Key/value pairs –Container adapters Containers have some common functions

 2003 Prentice Hall, Inc. All rights reserved. 3 STL Container Classes Sequence containers –vector –deque –list Associative containers –set –multiset –map –multimap Container adapters –stack –queue –priority_queue

 2003 Prentice Hall, Inc. All rights reserved. 4 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

 2003 Prentice Hall, Inc. All rights reserved. 5 Introduction to Iterators Usage –std::istream_iterator 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 outputInt(cout) Can output int s to cout *outputInt = 7 –Outputs 7 to cout ++outputInt –Advances iterator so we can output next int

 2003 Prentice Hall, Inc. All rights reserved. 6 Iterator Categories 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

 2003 Prentice Hall, Inc. All rights reserved. 7 Iterator Types Supported 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

 2003 Prentice Hall, Inc. All rights reserved. 8 Iterator Operations 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

 2003 Prentice Hall, Inc. All rights reserved. 9 Iterator Operations Bidirectional –--p, p-- Random access –p + i, p += i –p - i, p -= i –p[i] –p < p1, p <= p1 –p > p1, p >= p1

 2003 Prentice Hall, Inc. All rights reserved. 10 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

 2003 Prentice Hall, Inc. All rights reserved. 11 Sequence Containers Three sequence containers –vector - based on arrays –deque - based on arrays –list - robust linked list

 2003 Prentice Hall, Inc. All rights reserved. 12 vector Sequence Container 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

 2003 Prentice Hall, Inc. All rights reserved. 13 vector Sequence Container Declarations –std::vector v; type : int, float, etc. Iterators –std::vector ::const_iterator iterVar; const_iterator cannot modify elements –std::vector ::reverse_iterator iterVar; Visits elements in reverse order (end to beginning) Use rbegin to get starting point Use rend to get ending point

 2003 Prentice Hall, Inc. All rights reserved. 14 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 v(a, a + SIZE) Creates vector v with elements from array a up to (not including) a + SIZE

 2003 Prentice Hall, Inc. All rights reserved. 15 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

 2003 Prentice Hall, Inc. All rights reserved. 16 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

 2003 Prentice Hall, Inc. All rights reserved. Outline 17 1 // Fig : fig21_14.cpp 2 // Demonstrating standard library vector class template. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include // vector class-template definition // prototype for function template printVector 12 template 13 void printVector( const std::vector &integers2 ); int main() 16 { 17 const int SIZE = 6; 18 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; std::vector integers; 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 int s. Call member functions.

 2003 Prentice Hall, Inc. All rights reserved. Outline // function push_back is in every sequence collection 28 integers.push_back( 2 ); 29 integers.push_back( 3 ); 30 integers.push_back( 4 ); cout << "\nThe size of integers is: " << integers.size() 33 << "\nThe capacity of integers is: " 34 << integers.capacity(); cout << "\n\nOutput array using pointer notation: "; for ( int *ptr = array; ptr != array + SIZE; ++ptr ) 39 cout << *ptr << ' '; cout << "\nOutput vector using iterator notation: "; 42 printVector( integers ); cout << "\nReversed contents of vector integers: "; 45 Add elements to end of vector using push_back.

 2003 Prentice Hall, Inc. All rights reserved. Outline 19 fig21_14.cpp (3 of 3) 46 std::vector ::reverse_iterator reverseIterator; for ( reverseIterator = integers.rbegin(); 49 reverseIterator!= integers.rend(); 50 ++reverseIterator ) 51 cout << *reverseIterator << ' '; cout << endl; return 0; } // end main // function template for outputting vector elements 60 template 61 void printVector( const std::vector &integers2 ) 62 { 63 std::vector ::const_iterator constIterator; for ( constIterator = integers2.begin(); 66 constIterator != integers2.end(); 67 constIterator++ ) 68 cout << *constIterator << ' '; } // end function printVector Walk through vector backwards using a reverse_iterator. Template function to walk through vector forwards.

 2003 Prentice Hall, Inc. All rights reserved. Outline 20 The initial size of v is: 0 The initial capacity of v is: 0 The size of v is: 3 The capacity of v is: 4 Contents of array a using pointer notation: Contents of vector v using iterator notation: Reversed contents of vector v: 4 3 2

 2003 Prentice Hall, Inc. All rights reserved. 21 list Sequence Container list container –Header –Efficient insertion/deletion anywhere in container –Doubly-linked list (two pointers per node) –Bidirectional iterators –std::list name;

 2003 Prentice Hall, Inc. All rights reserved. 22 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 ); Merges the list, otherObject, into list t, sorted –t.unique(); Removes duplicate elements

 2003 Prentice Hall, Inc. All rights reserved. 23 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

 2003 Prentice Hall, Inc. All rights reserved. 24 deque Sequence Container deque : double-ended queue –Header –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)

 2003 Prentice Hall, Inc. All rights reserved. Outline 25 1 // Fig : fig21_18.cpp 2 // Standard library class deque test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // deque class-template definition 9 #include // copy algorithm int main() 12 { 13 std::deque values; 14 std::ostream_iterator output( cout, " " ); // insert elements in values 17 values.push_front( 2.2 ); 18 values.push_front( 3.5 ); 19 values.push_back( 1.1 ); cout << "values contains: "; // use subscript operator to obtain elements of values 24 for ( int i = 0; i < values.size(); ++i ) 25 cout << values[ i ] << ' '; 26 Create a deque, use member functions.

 2003 Prentice Hall, Inc. All rights reserved. Outline values.pop_front(); // remove first element cout << "\nAfter pop_front, values contains: "; 30 std::copy( values.begin(), values.end(), output ); // use subscript operator to modify element at location 1 33 values[ 1 ] = 5.4; cout << "\nAfter values[ 1 ] = 5.4, values contains: "; 36 std::copy( values.begin(), values.end(), output ); cout << endl; return 0; } // end main values contains: After pop_front, values contains: After values[ 1 ] = 5.4, values contains:

 2003 Prentice Hall, Inc. All rights reserved. 27 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

 2003 Prentice Hall, Inc. All rights reserved. 28 multiset Associative Container multiset –Header –Fast storage, retrieval of values –Allows duplicates –Bidirectional iterators Ordering of elements –Done by comparator function object Used when creating multiset –For integer multiset less comparator function object multiset > myObject; Elements will be sorted in ascending order

 2003 Prentice Hall, Inc. All rights reserved. 29 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

 2003 Prentice Hall, Inc. All rights reserved. 30 set Associative Container set –Header –Implementation identical to multiset –Unique keys Duplicates ignored and not inserted –Supports bidirectional iterators (but not random access) –std::set > name;

 2003 Prentice Hall, Inc. All rights reserved. 31 multimap Associative Container multimap –Header –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

 2003 Prentice Hall, Inc. All rights reserved. 32 multimap Associative Container Example std::multimap > mmapObject; –Key type int –Value type double –Sorted in ascending order typedef std::multimap > 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

 2003 Prentice Hall, Inc. All rights reserved. Outline 33 1 // Fig : fig21_21.cpp 2 // Standard library class multimap test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // map class-template definition 9 10 // define short name for multimap type used in this program 11 typedef std::multimap > mmid; int main() 14 { 15 mmid pairs; cout << "There are currently " << pairs.count( 15 ) 18 << " pairs with key 15 in the multimap\n"; // 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 ) ); 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.

 2003 Prentice Hall, Inc. All rights reserved. Outline // insert five value_type objects in pairs 29 pairs.insert( mmid::value_type( 30, ) ); 30 pairs.insert( mmid::value_type( 10, ) ); 31 pairs.insert( mmid::value_type( 25, ) ); 32 pairs.insert( mmid::value_type( 20, ) ); 33 pairs.insert( mmid::value_type( 5, ) ); cout << "Multimap pairs contains:\nKey\tValue\n"; // use const_iterator to walk through elements of pairs 38 for ( mmid::const_iterator iter = pairs.begin(); 39 iter != pairs.end(); ++iter ) 40 cout first << '\t' 41 second << '\n'; cout << endl; return 0; } // end main Use iterator to print entire multimap.

 2003 Prentice Hall, Inc. All rights reserved. Outline 35 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

 2003 Prentice Hall, Inc. All rights reserved. 36 map Associative Container map –Header –Like multimap, but only unique key/value pairs One-to-one mapping (duplicates ignored) –Use [] to access values –Example: for map object m m[30] = ; Sets the value of key 30 to –If subscript not in map, creates new key/value pair Type declaration –std::map >;

 2003 Prentice Hall, Inc. All rights reserved. Outline 37 1 // Fig : fig21_22.cpp 2 // Standard library class map test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // map class-template definition 9 10 // define short name for map type used in this program 11 typedef std::map > mid; int main() 14 { 15 mid pairs; // insert eight value_type objects in pairs 18 pairs.insert( mid::value_type( 15, 2.7 ) ); 19 pairs.insert( mid::value_type( 30, ) ); 20 pairs.insert( mid::value_type( 5, ) ); 21 pairs.insert( mid::value_type( 10, ) ); 22 pairs.insert( mid::value_type( 25, ) ); 23 pairs.insert( mid::value_type( 5, ) ); // dupe ignored 24 pairs.insert( mid::value_type( 20, ) ); 25 pairs.insert( mid::value_type( 15, 99.3 ) ); // dupe ignored 26 Again, use typedef s to simplify declaration. Duplicate keys ignored.

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << "pairs contains:\nKey\tValue\n"; // use const_iterator to walk through elements of pairs 30 for ( mid::const_iterator iter = pairs.begin(); 31 iter != pairs.end(); ++iter ) 32 cout first << '\t' 33 second << '\n'; // use subscript operator to change value for key pairs[ 25 ] = ; // use subscript operator insert value for key pairs[ 40 ] = ; cout << "\nAfter subscript operations, pairs contains:" 42 << "\nKey\tValue\n"; for ( mid::const_iterator iter2 = pairs.begin(); 45 iter2 != pairs.end(); ++iter2 ) 46 cout first << '\t' 47 second << '\n'; cout << endl; return 0; } // end main Can use subscript operator to add or change key-value pairs.

 2003 Prentice Hall, Inc. All rights reserved. Outline 39 pairs contains: Key Value After subscript operations, pairs contains: Key Value

 2003 Prentice Hall, Inc. All rights reserved. 40 Container Adapters Container adapters –stack, queue and priority_queue –Do not support iterators –Programmer can select implementation –Member functions push and pop

 2003 Prentice Hall, Inc. All rights reserved. 41 stack Adapter stack –Header –Insertions and deletions at one end –Last-in, first-out (LIFO) data structure –Can use vector, list, or deque (default) –Declarations stack > myStack; stack > myOtherStack; stack anotherStack; // default deque vector, list –Implementation of stack (default deque ) –Does not change behavior, just performance ( deque and vector fastest)

 2003 Prentice Hall, Inc. All rights reserved. Outline 42 1 // Fig : fig21_23.cpp 2 // Standard library adapter stack test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // stack adapter definition 9 #include // vector class-template definition 10 #include // list class-template definition // popElements function-template prototype 13 template 14 void popElements( T &stackRef ); int main() 17 { 18 // stack with default underlying deque 19 std::stack intDequeStack; // stack with underlying vector 22 std::stack > intVectorStack; // stack with underlying list 25 std::stack > intListStack; 26 Create stacks with various implementations.

 2003 Prentice Hall, Inc. All rights reserved. Outline // 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 ); } // end for // 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 ); cout << endl; return 0; } // end main 48 Use member function push.

 2003 Prentice Hall, Inc. All rights reserved. Outline // pop elements from stack object to which stackRef refers 50 template 51 void popElements( T &stackRef ) 52 { 53 while ( !stackRef.empty() ) { 54 cout << stackRef.top() << ' '; // view top element 55 stackRef.pop(); // remove top element } // end while } // end function popElements Popping from intDequeStack: Popping from intVectorStack: Popping from intListStack:

 2003 Prentice Hall, Inc. All rights reserved. 45 queue Adapter queue –Header –Insertions at back, deletions at front –First-in-first-out (FIFO) data structure –Implemented with list or deque (default) std::queue values; Functions –push( element ) Same as push_back, add to end –pop( element ) Implemented with pop_front, remove from front –empty() –size()

 2003 Prentice Hall, Inc. All rights reserved. Outline 46 1 // Fig : fig21_24.cpp 2 // Standard library adapter queue test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // queue adapter definition 9 10 int main() 11 { 12 std::queue values; // push elements onto queue values 15 values.push( 3.2 ); 16 values.push( 9.8 ); 17 values.push( 5.4 ); cout << "Popping from values: "; while ( !values.empty() ) { 22 cout << values.front() << ' '; // view front element 23 values.pop(); // remove element } // end while 26 Create queue, add values using push.

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << endl; return 0; } // end main Popping from values:

 2003 Prentice Hall, Inc. All rights reserved. 48 priority_queue Adapter priority_queue –Header –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 default, programmer can specify other comparator –Functions push(value), pop(value) top() –View top element size() empty()

 2003 Prentice Hall, Inc. All rights reserved. Outline 49 1 // Fig : fig21_25.cpp 2 // Standard library adapter priority_queue test program. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // priority_queue adapter definition 9 10 int main() 11 { 12 std::priority_queue priorities; // push elements onto priorities 15 priorities.push( 3.2 ); 16 priorities.push( 9.8 ); 17 priorities.push( 5.4 ); cout << "Popping from priorities: "; while ( !priorities.empty() ) { 22 cout << priorities.top() << ' '; // view top element 23 priorities.pop(); // remove top element } // end while 26 Create priority queue.Insert items using push. When using pop, highest priority (largest) items removed first.

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << endl; return 0; } // end main Popping from priorities:

 2003 Prentice Hall, Inc. All rights reserved. 51 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 –

 2003 Prentice Hall, Inc. All rights reserved. 52 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, ""

 2003 Prentice Hall, Inc. All rights reserved. 53 equal and mismatch 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 first mismatch –If no mismatch, pair iterators equal to last item pair myPairObject; myPairObject = mismatch( iter1, iter2, iter3);

 2003 Prentice Hall, Inc. All rights reserved. 54 remove, remove_if, remove_copy and remove_copy_if remove –remove( iter1, iter2, value); –Removes all instances of value in range ( iter1,iter2 ) 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

 2003 Prentice Hall, Inc. All rights reserved. 55 remove, remove_if, remove_copy and remove_copy_if remove_if –Like remove Returns iterator to last element Removes elements that return true for specified function remove_if(iter1,iter2, function); Elements passed to function, which returns a bool remove_copy_if –Like remove_copy and remove_if –Copies range of elements to iter3, except those for which function returns true remove_copy_if(iter1, iter2, iter3, function);

 2003 Prentice Hall, Inc. All rights reserved. 56 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

 2003 Prentice Hall, Inc. All rights reserved. 57 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

 2003 Prentice Hall, Inc. All rights reserved. 58 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

 2003 Prentice Hall, Inc. All rights reserved. 59 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

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

 2003 Prentice Hall, Inc. All rights reserved. Outline if ( location != v.end() ) 29 cout << "\n\nFound 16 at location " 30 << ( location - v.begin() ); 31 else 32 cout << "\n\n16 not found"; // locate first occurrence of 100 in v 35 location = std::find( v.begin(), v.end(), 100 ); if ( location != v.end() ) 38 cout << "\nFound 100 at location " 39 << ( location - v.begin() ); 40 else 41 cout << "\n100 not found"; // locate first occurrence of value greater than 10 in v 44 location = std::find_if( v.begin(), v.end(), greater10 ); 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

 2003 Prentice Hall, Inc. All rights reserved. Outline // sort elements of v 54 std::sort( v.begin(), v.end() ); cout << "\n\nVector v after sort: "; 57 std::copy( v.begin(), v.end(), output ); // 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"; // 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"; cout << endl; return 0; } // end main 76

 2003 Prentice Hall, Inc. All rights reserved. Outline // determine whether argument is greater than bool greater10( int value ) 79 { 80 return value > 10; } // end function greater10 Vector v contains: Found 16 at location not found The first value greater than 10 is 17 found at location 2 Vector v after sort: was found in v 100 was not found in v

 2003 Prentice Hall, Inc. All rights reserved. 64 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

 2003 Prentice Hall, Inc. All rights reserved. 65 Set Operations includes(iter1, iter2, iter3, iter4) –Returns true if iter1-iter2 contains iter3-iter4 –Both ranges must be sorted a1: a2: 1 3 a1 includes a3 set_difference(iter1, iter2, iter3, iter4, iter5) –Copies elements in first set (1-2) that are not in second set (3-4) into iter5 set_intersection(iter1, iter2, iter3, iter4, iter5) –Copies common elements from the two sets (1-2, 3-4) into iter5

 2003 Prentice Hall, Inc. All rights reserved. 66 Set Operations set_symmetric_difference(iter1, iter2, iter3, iter4, iter5) –Copies elements in set (1-2) but not set (3-4), and vice versa, into iter5 a1: a2: set_symmetric_difference: –Both sets must be sorted set_union( iter1, iter2, iter3, iter4, iter5) –Copies elements in either or both sets to iter5 –Both sets must be sorted

 2003 Prentice Hall, Inc. All rights reserved. Outline 67 1 // Fig : fig21_35.cpp 2 // Standard library algorithms includes, set_difference, 3 // set_intersection, set_symmetric_difference and set_union. 4 #include 5 6 using std::cout; 7 using std::endl; 8 9 #include // algorithm definitions 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 output( cout, " " ); 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

 2003 Prentice Hall, Inc. All rights reserved. Outline // 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"; // 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"; int difference[ SIZE1 ]; // determine elements of a1 not in a2 41 int *ptr = std::set_difference( a1, a1 + SIZE1, 42 a2, a2 + SIZE2, difference ); cout << "\n\nset_difference of a1 and a2 is: "; 45 std::copy( difference, ptr, output ); int intersection[ SIZE1 ]; // determine elements in both a1 and a2 50 ptr = std::set_intersection( a1, a1 + SIZE1, 51 a2, a2 + SIZE2, intersection ); 52

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << "\n\nset_intersection of a1 and a2 is: "; 54 std::copy( intersection, ptr, output ); int symmetric_difference[ SIZE1 ]; // 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 ); cout << "\n\nset_symmetric_difference of a1 and a2 is: "; 64 std::copy( symmetric_difference, ptr, output ); int unionSet[ SIZE3 ]; // determine elements that are in either or both sets 69 ptr = std::set_union( a1, a1 + SIZE1, 70 a3, a3 + SIZE2, unionSet ); cout << "\n\nset_union of a1 and a3 is: "; 73 std::copy( unionSet, ptr, output ); cout << endl; return 0; } // end main

 2003 Prentice Hall, Inc. All rights reserved. Outline 70 a1 contains: a2 contains: a3 contains: a1 includes a2 a1 does not include a3 set_difference of a1 and a2 is: set_intersection of a1 and a2 is: set_symmetric_difference of a1 and a2 is: set_union of a1 and a3 is:

 2003 Prentice Hall, Inc. All rights reserved. 71 min and max min(value1, value2) –Returns smaller element max(value1, value2) –Returns larger element