Introduction to the Standard Template Library STL STL
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 – Only an introduction to STL, a huge class library 2003 Prentice Hall, Inc. All rights reserved. 1
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< int > input. Int( cin ) • Can read input from cin • *input. Int – Dereference to read first int from cin • ++input. Int – Go to next in stream – std: : ostream_iterator< int > output. Int(cout) • Can output ints to cout • *output. Int = 7 – Outputs 7 to cout • ++output. Int – 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 = p 1 – p == p 1, p != p 1 • Output iterators – *p – p = p 1 • 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 < p 1, p <= p 1 p > p 1, p >= p 1 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 – <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 <type> v; • type: int, float, etc. • Iterators – std: : vector<type>: : const_iterator iter. Var; • const_iterator cannot modify elements – std: : vector<type>: : reverse_iterator iter. Var; • 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<type> 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 + SIZE) • Inserts array elements (up to, but not including array + SIZE) into vector – v. erase( iterator ) • Remove element from container – v. erase( iter 1, iter 2 ) • Remove elements starting from iter 1 and up to (not including) iter 2 – 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[element. Number] = value; • Assign value to an element – v. at(element. Number) = value; • As above, with range checking • out_of_bounds exception 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 14: fig 21_14. cpp // Demonstrating standard library vector class template. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 #include <vector> 10 11 12 13 // prototype for function template print. Vector template < class T > void print. Vector( const std: : vector< T > &integers 2 ); 14 15 16 17 18 int main() { Create a const int SIZE = 6; int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; Outline // vector class-template definition 19 20 std: : vector< int > integers; 21 22 23 24 25 cout << << vector of ints. Call member functions. "The initial size of integers is: " integers. size() "n. The initial capacity of integers is: " integers. capacity(); 26 2003 Prentice Hall, Inc. All rights reserved. 17
27 28 29 30 // function push_back integers. push_back( 2 integers. push_back( 3 integers. push_back( 4 31 32 33 34 cout << "n. The size of integers is: " << integers. size() << "n. The capacity of integers is: " << integers. capacity(); 35 36 cout << "nn. Output array using pointer notation: " ; 37 38 39 for ( int *ptr = array; ptr != array + SIZE; ++ptr ) cout << *ptr << ' '; 40 41 42 cout << "n. Output vector using iterator notation: "; print. Vector( integers ); 43 44 cout << "n. Reversed contents of vector integers: " ; is in every sequence collection ); ); ); Add elements to end of Outline vector using push_back. 45 2003 Prentice Hall, Inc. All rights reserved. 18
46 std: : vector< int >: : reverse_iterator reverse. Iterator; 47 48 49 50 51 for ( reverse. Iterator = integers. rbegin(); reverse. Iterator!= integers. rend(); ++reverse. Iterator ) cout << *reverse. Iterator << ' '; 52 53 cout << endl; 54 55 return 0; 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 } // end main // function template for outputting vector elements template < class T > void print. Vector( const std: : vector< T > &integers 2 ) { std: : vector< T >: : const_iterator const. Iterator; Outline Walk through vector fig 21_14. cpp backwards using (3 of 3) a reverse_iterator. Template function to walk through vector forwards. for ( const. Iterator = integers 2. begin(); const. Iterator != integers 2. end(); const. Iterator++ ) cout << *const. Iterator << ' '; } // end function print. Vector 2003 Prentice Hall, Inc. All rights reserved. 19
The The initial size of v is: 0 initial capacity of v is: 0 size of v is: 3 capacity of v is: 4 Outline 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 2003 Prentice Hall, Inc. All rights reserved. 20
21 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; 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, other. Object ); • Inserts values from other. Object before iterator – t. merge( other. Object ); • Merges the list, other. Object, into list t, sorted – t. unique(); • Removes duplicate elements 2003 Prentice Hall, Inc. All rights reserved.
23 list Sequence Container • list functions – t. swap(other. Object); • Exchange contents – t. assign(iterator 1, iterator 2); • 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 <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) 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 18: fig 21_18. cpp // Standard library class deque test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <deque> #include <algorithm> 10 11 12 13 14 int main() { std: : deque< double > values; std: : ostream_iterator< double > output( cout, " " ); Outline // deque class-template definition // copy algorithm Create a deque, use member functions. 15 16 17 18 19 // insert elements in values. push_front( 2. 2 ); values. push_front( 3. 5 ); values. push_back( 1. 1 ); 20 21 cout << "values contains: "; 22 23 24 25 // use subscript operator to obtain elements of values for ( int i = 0; i < values. size(); ++i ) cout << values[ i ] << ' '; 26 2003 Prentice Hall, Inc. All rights reserved. 25
27 values. pop_front(); 28 29 30 cout << "n. After pop_front, values contains: "; std: : copy( values. begin(), values. end(), output ); 31 32 33 // use subscript operator to modify element at location 1 values[ 1 ] = 5. 4; 34 35 36 37 38 39 40 41 42 // remove first element Outline cout << "n. After values[ 1 ] = 5. 4, values contains: " ; std: : copy( values. begin(), values. end(), output ); cout << endl; return 0; } // end main values contains: 3. 5 2. 2 1. 1 After pop_front, values contains: 2. 2 1. 1 After values[ 1 ] = 5. 4, values contains: 2. 2 5. 4 2003 Prentice Hall, Inc. All rights reserved. 26
27 Associative Containers • Associative containers – Direct access to store/retrieve elements – Uses keys (search keys) – 4 types: multiset, 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 <set> 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<int> comparator function object • multiset< int, std: : less<int> > my. Object; • 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 <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; 2003 Prentice Hall, Inc. All rights reserved.
31 multimap Associative Container • multimap – Header <map> – Fast storage and retrieval of keys and associated values • Has key/value pairs – Duplicate keys allowed (multiple values for a single key) • One-to-many relationship • i. e. , one student can take many courses – Insert pair objects (with a key and value) – Bidirectional iterators 2003 Prentice Hall, Inc. All rights reserved.
32 multimap Associative Container • Example std: : multimap< int, double, std: : less< int > > mmap. Object; – Key type int – Value type double – Sorted in ascending order typedef std: : multimap<int, double, std: : less<int>> mmid; mmid mmap. Object; mmap. Object. 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.
1 2 3 // Fig. 21: fig 21_21. cpp // Standard library class multimap test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <map> 9 10 11 // define short name for multimap type used in this program typedef std: : multimap< int, double, std: : less< int > > mmid; 12 13 14 15 int main() { mmid pairs; 16 17 18 19 20 21 22 23 24 25 26 // map class-template definition Outline Definition for a multimap that maps integer keys to double values. Create multimap and insert key-value pairs. cout << "There are currently " << pairs. count( 15 ) << " pairs with key 15 in the multimapn"; // insert two value_type objects in pairs. insert( mmid: : value_type( 15, 2. 7 ) ); pairs. insert( mmid: : value_type( 15, 99. 3 ) ); cout << "After inserts, there are " << pairs. count( 15 ) << " pairs with key 15nn" ; 2003 Prentice Hall, Inc. All rights reserved. 33
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 Use iterator to cout << "Multimap pairs contains: n. Keyt. Valuen"; print entire multimap. // use const_iterator to walk through elements of pairs for ( mmid: : const_iterator iter = pairs. begin(); iter != pairs. end(); ++iter ) cout << iter->first << 't' << iter->second << 'n'; 42 43 cout << endl; 44 45 return 0; 46 47 Outline // insert five value_type objects in pairs. insert( mmid: : value_type( 30, 111. 11 ) ); pairs. insert( mmid: : value_type( 10, 22. 22 ) ); pairs. insert( mmid: : value_type( 25, 33. 333 ) ); pairs. insert( mmid: : value_type( 20, 9. 345 ) ); pairs. insert( mmid: : value_type( 5, 77. 54 ) ); } // end main 2003 Prentice Hall, Inc. All rights reserved. 34
There are currently 0 pairs with key 15 in the multimap After inserts, there are 2 pairs with key 15 Outline 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 2003 Prentice Hall, Inc. All rights reserved. 35
36 map Associative Container • map – Header <map> – Like multimap, but only unique key/value pairs • One-to-one mapping (duplicates ignored) – Use [] to access values – Example: for map object m m[30] = 4000. 21; • Sets the value of key 30 to 4000. 21 – If subscript not in map, creates new key/value pair • Type declaration – std: : map< int, double, std: : less< int > >; 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 22: fig 21_22. cpp // Standard library class map test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <map> 9 10 11 // define short name for map type used in this program typedef std: : map< int, double, std: : less< int > > mid; 12 13 14 15 int main() { mid pairs; 16 17 18 19 20 21 22 23 24 25 Outline Again, use typedefs to simplify declaration. // map class-template definition // insert eight value_type objects in pairs. insert( mid: : value_type( 15, 2. 7 ) ); pairs. insert( mid: : value_type( 30, 111. 11 ) ); pairs. insert( mid: : value_type( 5, 1010. 1 ) ); pairs. insert( mid: : value_type( 10, 22. 22 ) ); pairs. insert( mid: : value_type( 25, 33. 333 ) ); pairs. insert( mid: : value_type( 5, 77. 54 ) ); // dupe ignored pairs. insert( mid: : value_type( 20, 9. 345 ) ); pairs. insert( mid: : value_type( 15, 99. 3 ) ); // dupe ignored Duplicate keys ignored. 26 2003 Prentice Hall, Inc. All rights reserved. 37
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 cout << "pairs contains: n. Keyt. Valuen"; // use const_iterator to walk through elements of pairs for ( mid: : const_iterator iter = pairs. begin(); iter != pairs. end(); ++iter ) cout << iter->first << 't' Can use subscript << iter->second << 'n'; operator to add or change key-value pairs. // use subscript operator to change value for key 25 pairs[ 25 ] = 9999. 99; // use subscript operator insert value for key 40 pairs[ 40 ] = 8765. 43; cout << "n. After subscript operations, pairs contains: " << "n. Keyt. Valuen"; for ( mid: : const_iterator iter 2 = pairs. begin(); iter 2 != pairs. end(); ++iter 2 ) cout << iter 2 ->first << 't' << iter 2 ->second << 'n'; 48 49 cout << endl; 50 51 return 0; 52 53 Outline } // end main 2003 Prentice Hall, Inc. All rights reserved. 38
pairs contains: Key Value 5 1010. 1 10 22. 22 15 2. 7 20 9. 345 25 33. 333 30 111. 11 Outline After subscript operations, pairs contains: Key Value 5 1010. 1 10 22. 22 15 2. 7 20 9. 345 25 9999. 99 30 111. 11 40 8765. 43 2003 Prentice Hall, Inc. All rights reserved. 39
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 <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> > my. Stack; stack<type, list<type> > my. Other. Stack; stack<type> another. Stack; // 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.
1 2 3 // Fig. 21. 23: fig 21_23. cpp // Standard library adapter stack test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 #include <stack> #include <vector> #include <list> 11 12 13 14 // pop. Elements function-template prototype template< class T > void pop. Elements( T &stack. Ref ); 15 16 17 18 19 int main() { // stack with default underlying deque std: : stack< int > int. Deque. Stack; Outline // stack adapter definition // vector class-template definition // list class-template definition Create stacks with various implementations. 20 21 22 // stack with underlying vector std: : stack< int, std: : vector< int > > int. Vector. Stack; 23 24 25 // stack with underlying list std: : stack< int, std: : list< int > > int. List. Stack; 26 2003 Prentice Hall, Inc. All rights reserved. 42
27 28 29 30 31 // push the values 0 -9 onto each stack for ( int i = 0; i < 10; ++i ) { int. Deque. Stack. push( i ); int. Vector. Stack. push( i ); int. List. Stack. push( i ); 32 33 } // end for 34 35 36 37 38 39 40 41 // display and remove elements from each stack cout << "Popping from int. Deque. Stack: "; pop. Elements( int. Deque. Stack ); cout << "n. Popping from int. Vector. Stack: "; pop. Elements( int. Vector. Stack ); cout << "n. Popping from int. List. Stack: "; pop. Elements( int. List. Stack ); 42 43 cout << endl; 44 45 return 0; 46 47 Outline Use member function push. } // end main 48 2003 Prentice Hall, Inc. All rights reserved. 43
49 50 51 52 53 54 55 56 57 58 59 // pop elements from stack object to which stack. Ref refers template< class T > void pop. Elements( T &stack. Ref ) { while ( !stack. Ref. empty() ) { cout << stack. Ref. top() << ' '; // view top element stack. Ref. pop(); // remove top element Outline } // end while } // end function pop. Elements Popping from int. Deque. Stack: 9 8 7 6 5 4 3 2 1 0 Popping from int. Vector. Stack: 9 8 7 6 5 4 3 2 1 0 Popping from int. List. Stack: 9 8 7 6 5 4 3 2 1 0 2003 Prentice Hall, Inc. All rights reserved. 44
45 queue Adapter • queue – – Header <queue> Insertions at back, deletions at front First-in-first-out (FIFO) data structure Implemented with list or deque (default) • std: : queue<double> values; • Functions – push( element ) • Same as push_back, add to end – pop( element ) • Implemented with pop_front, remove from front – empty() – size() 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 24: fig 21_24. cpp // Standard library adapter queue test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <queue> 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Outline // queue adapter definition int main() { std: : queue< double > values; // push elements values. push( 3. 2 values. push( 9. 8 values. push( 5. 4 Create queue, add values using push. onto queue values ); ); ); cout << "Popping from values: "; while ( !values. empty() ) { cout << values. front() << ' '; values. pop(); // view front element // remove element } // end while 26 2003 Prentice Hall, Inc. All rights reserved. 46
27 cout << endl; 28 29 return 0; 30 31 Outline } // end main Popping from values: 3. 2 9. 8 5. 4 2003 Prentice Hall, Inc. All rights reserved. 47
48 priority_queue Adapter • priority_queue – – Header <queue> Insertions happen in sorted order, deletions from front Implemented with vector (default) or deque Highest priority element always removed first • Heapsort algorithm puts largest elements at front • less<T> default, programmer can specify other comparator – Functions • push(value), pop(value) • top() – View top element • size() • empty() 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 25: fig 21_25. cpp // Standard library adapter priority_queue test program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <queue> 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Outline // priority_queue adapter definition Create priority queue. int main() { std: : priority_queue< double > priorities; // push elements priorities. push( onto priorities 3. 2 ); 9. 8 ); 5. 4 ); Insert items using push. When using pop, highest priority (largest) items removed first. cout << "Popping from priorities: " ; while ( !priorities. empty() ) { cout << priorities. top() << ' '; priorities. pop(); // view top element // remove top element } // end while 26 2003 Prentice Hall, Inc. All rights reserved. 49
27 cout << endl; 28 29 return 0; 30 31 Outline } // end main Popping from priorities: 9. 8 5. 4 3. 2 2003 Prentice Hall, Inc. All rights reserved. 50
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 – <algorithm> 2003 Prentice Hall, Inc. All rights reserved.
52 fill, fill_n, generate and generate_n • Functions to change containers – fill(iterator 1, iterator 2, value); • Sets range of elements to value – fill_n(iterator 1, n, value); • Sets n elements to value, starting at iterator 1 – generate(iterator 1, iterator 2, function); • Like fill, but calls function to set each value – generate(iterator 1, 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(iterator 1, iterator 2, iterator 3); • Compares sequence from iterator 1 to iterator 2 with sequence beginning at iterator 3 – 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 < iterator, iterator > my. Pair. Object; my. Pair. Object = mismatch( iter 1, iter 2, iter 3); 2003 Prentice Hall, Inc. All rights reserved.
remove, remove_if, remove_copy and remove_copy_if • remove – remove( iter 1, iter 2, value); – Removes all instances of value in range (iter 1, iter 2) • remove_copy – Copies one vector to another while removing an element – remove_copy(iter 1, iter 2, iter 3, value); • Copies elements not equal to value into iter 3 (output iterator) • Uses range iter 1, iter 2 2003 Prentice Hall, Inc. All rights reserved. 54
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(iter 1, iter 2, function); • Elements passed to function, which returns a bool • remove_copy_if – Like remove_copy and remove_if – Copies range of elements to iter 3, except those for which function returns true remove_copy_if(iter 1, iter 2, iter 3, function); 2003 Prentice Hall, Inc. All rights reserved. 55
replace, replace_if, replace_copy and replace_copy_if • Functions – replace( iter 1, iter 2, value, newvalue ); • Like remove, except replaces value with newvalue – replace_if( iter 1, iter 2, function, newvalue ); • Replaces value if function returns true – replace_copy(iter 1, iter 2, iter 3, value, newvalue); • Replaces and copies elements to iter 3 • Does not affect originals – replace_copy_if( iter 1, iter 2, iter 3, function, newvalue ); • Replaces and copies elements to iter 3 if function returns true 2003 Prentice Hall, Inc. All rights reserved. 56
57 Mathematical Algorithms • random_shuffle(iter 1, iter 2) – Randomly mixes elements in range • count(iter 1, iter 2, value) – Returns number of instances of value in range • count_if(iter 1, iter 2, function) – Counts number of instances that return true • min_element(iter 1, iter 2) – Returns iterator to smallest element • max_element(iter 1, iter 2) – Returns iterator to largest element 2003 Prentice Hall, Inc. All rights reserved.
58 Mathematical Algorithms • accumulate(iter 1, iter 2) – Returns sum of elements in range • for_each(iter 1, iter 2, function) – Calls function on every element in range – Does not modify element • transform(iter 1, iter 2, iter 3, function) – Calls function for all elements in range of iter 1, iter 2, copies result to iter 3 2003 Prentice Hall, Inc. All rights reserved.
59 Basic Searching and Sorting Algorithms • find(iter 1, iter 2, value) – Returns iterator to first instance of value (in range) • find_if(iter 1, iter 2, function) – Like find – Returns iterator when function returns true • sort(iter 1, iter 2) – Sorts elements in ascending order • binary_search(iter 1, iter 2, value) – Searches ascending sorted list for value – Uses binary search 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 21. 31: fig 21_31. cpp // Standard library search and sort algorithms. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <algorithm> #include <vector> 10 11 bool greater 10( int value ); 12 13 14 15 16 int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 17 18 19 20 21 22 23 24 25 26 Outline // algorithm definitions // vector class-template definition // prototype std: : vector< int > v( a, a + SIZE ); std: : ostream_iterator< int > output( cout, " " ); cout << "Vector v contains: "; std: : copy( v. begin(), v. end(), output ); // locate first occurrence of 16 in v std: : vector< int >: : iterator location; location = std: : find( v. begin(), v. end(), 16 ); 2003 Prentice Hall, Inc. All rights reserved. 60
27 28 29 30 31 32 33 34 35 // locate first occurrence of 100 in v location = std: : find( v. begin(), v. end(), 100 ); 36 37 38 39 40 41 if ( location != v. end() ) cout << "n. Found 100 at location " << ( location - v. begin() ); else cout << "n 100 not found"; 42 43 44 // locate first occurrence of value greater than 10 in v location = std: : find_if( v. begin(), v. end(), greater 10 ); 45 46 47 48 49 50 51 if ( location != v. end() ) cout << "nn. The first value greater than 10 is " << *location << "nfound at location " << ( location - v. begin() ); else cout << "nn. No values greater than 10 were found" ; if ( location != v. end() ) cout << "nn. Found 16 at location " << ( location - v. begin() ); else cout << "nn 16 not found"; Outline 52 2003 Prentice Hall, Inc. All rights reserved. 61
53 54 // sort elements of v std: : sort( v. begin(), v. end() ); 55 56 57 cout << "nn. Vector v after sort: "; std: : copy( v. begin(), v. end(), output ); 58 59 60 61 62 63 // use binary_search to locate 13 in v if ( std: : binary_search( v. begin(), v. end(), 13 ) ) cout << "nn 13 was found in v"; else cout << "nn 13 was not found in v" ; 64 65 66 67 68 69 // use binary_search to locate 100 in v if ( std: : binary_search( v. begin(), v. end(), 100 ) ) cout << "n 100 was found in v"; else cout << "n 100 was not found in v" ; 70 71 cout << endl; 72 73 return 0; 74 75 Outline } // end main 76 2003 Prentice Hall, Inc. All rights reserved. 62
77 78 79 80 // determine whether argument is greater than 10 bool greater 10( int value ) { return value > 10; 81 82 } // end function greater 10 Outline 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 2003 Prentice Hall, Inc. All rights reserved. 63
64 swap, iter_swap and swap_ranges • swap(element 1, element 2) – Exchanges two values – swap( a[ 0 ], a[ 1 ] ); • iter_swap(iter 1, iter 2) – Exchanges the values to which the iterators refer • swap_ranges(iter 1, iter 2, iter 3) – Swap the elements from iter 1, iter 2 with elements beginning at iter 3 2003 Prentice Hall, Inc. All rights reserved.
65 Set Operations • includes(iter 1, iter 2, iter 3, iter 4) – Returns true if iter 1 -iter 2 contains iter 3 -iter 4 – Both ranges must be sorted a 1: 1 2 3 4 a 2: 1 3 a 1 includes a 3 • set_difference(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in first set (1 -2) that are not in second set (3 -4) into iter 5 • set_intersection(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies common elements from the two sets (1 -2, 3 -4) into iter 5 2003 Prentice Hall, Inc. All rights reserved.
66 Set Operations • set_symmetric_difference(iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in set (1 -2) but not set (3 -4), and vice versa, into iter 5 • a 1: 1 2 3 4 5 6 7 8 9 10 • a 2: 4 5 6 7 8 • set_symmetric_difference: 1 2 3 9 10 – Both sets must be sorted • set_union( iter 1, iter 2, iter 3, iter 4, iter 5) – Copies elements in either or both sets to iter 5 – Both sets must be sorted 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 // Fig. 21. 35: fig 21_35. cpp // Standard library algorithms includes, set_difference, // set_intersection, set_symmetric_difference and set_union. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 #include <algorithm> 10 11 12 13 14 15 16 17 int main() { const int SIZE 1 = 10, SIZE 2 = 5, SIZE 3 = 20; int a 1[ SIZE 1 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int a 2[ SIZE 2 ] = { 4, 5, 6, 7, 8 }; int a 3[ SIZE 2 ] = { 4, 5, 6, 11, 15 }; std: : ostream_iterator< int > output( cout, " " ); 18 19 20 21 22 23 24 Outline // algorithm definitions cout << "a 1 contains: "; std: : copy( a 1, a 1 + SIZE 1, output ); cout << "na 2 contains: "; std: : copy( a 2, a 2 + SIZE 2, output ); cout << "na 3 contains: "; std: : copy( a 3, a 3 + SIZE 2, output ); 25 2003 Prentice Hall, Inc. All rights reserved. 67
26 27 28 29 30 31 32 33 34 35 36 // determine whether set a 2 is completely contained in a 1 if ( std: : includes( a 1, a 1 + SIZE 1, a 2 + SIZE 2 ) ) cout << "nna 1 includes a 2"; else cout << "nna 1 does not include a 2" ; Outline // determine whether set a 3 is completely contained in a 1 if ( std: : includes( a 1, a 1 + SIZE 1, a 3 + SIZE 2 ) ) cout << "na 1 includes a 3"; else cout << "na 1 does not include a 3" ; 37 38 int difference[ SIZE 1 ]; 39 40 41 42 // determine elements of a 1 not in a 2 int *ptr = std: : set_difference( a 1, a 1 + SIZE 1, a 2 + SIZE 2, difference ); 43 44 45 cout << "nnset_difference of a 1 and a 2 is: "; std: : copy( difference, ptr, output ); 46 47 intersection[ SIZE 1 ]; 48 49 50 51 // determine elements in both a 1 and a 2 ptr = std: : set_intersection( a 1, a 1 + SIZE 1, a 2 + SIZE 2, intersection ); 52 2003 Prentice Hall, Inc. All rights reserved. 68
53 54 55 56 57 58 59 60 61 cout << "nnset_intersection of a 1 and a 2 is: "; std: : copy( intersection, ptr, output ); int symmetric_difference[ SIZE 1 ]; // determine elements of a 1 that are not in a 2 and // elements of a 2 that are not in a 1 ptr = std: : set_symmetric_difference ( a 1, a 1 + SIZE 1, a 2 + SIZE 2, symmetric_difference ); 62 63 64 cout << "nnset_symmetric_difference of a 1 and a 2 is: "; std: : copy( symmetric_difference, ptr, output ); 65 66 int union. Set[ SIZE 3 ]; 67 68 69 70 // determine elements that are in either or both sets ptr = std: : set_union( a 1, a 1 + SIZE 1, a 3 + SIZE 2, union. Set ); 71 72 73 74 75 76 77 78 79 Outline cout << "nnset_union of a 1 and a 3 is: "; std: : copy( union. Set, ptr, output ); cout << endl; return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. 69
a 1 contains: 1 2 3 4 5 6 7 8 9 10 a 2 contains: 4 5 6 7 8 a 3 contains: 4 5 6 11 15 Outline a 1 includes a 2 a 1 does not include a 3 set_difference of a 1 and a 2 is: 1 2 3 9 10 set_intersection of a 1 and a 2 is: 4 5 6 7 8 set_symmetric_difference of a 1 and a 2 is: 1 2 3 9 10 set_union of a 1 and a 3 is: 1 2 3 4 5 6 7 8 9 10 11 15 2003 Prentice Hall, Inc. All rights reserved. 70
71 min and max • min(value 1, value 2) – Returns smaller element • max(value 1, value 2) – Returns larger element 2003 Prentice Hall, Inc. All rights reserved.
- Slides: 71