Upload
washi
View
73
Download
0
Embed Size (px)
DESCRIPTION
STL Library - Overview. Standard template library accepted in July 1994 into C++ ANSI Standard STL library provides containers, iterators and algorithms designed to work efficiently work parametrically work orthogonally. vector. queue. map. previous. next. begin. end. - PowerPoint PPT Presentation
Citation preview
5/8/2002 1
STL Library - Overview
Standard template library accepted in July 1994 into C++ ANSI Standard
STL library provides containers, iterators and algorithms designed to work efficiently work parametrically work orthogonally
5/8/2002 2
Efficient library for basic data structures
Navigation of containers using iterator classes
Algorithms for their use
STL - Standard Template Library
vector queue map
begin end previous next
search functions sort functions
5/8/2002 3
STL Based on Templates
Parametric - instantiated with different
types
Components used with each other
Uses templates
Native types
User provided types
5/8/2002 4
STL - Standard Template Library
Parametric - types instantiated Library for data structures
Provides tools for navigation over containers using iterator classes
begin, end, previous, next Provides algorithms for their usesorting, searching functions
vectors maps queues
5/8/2002 5
Array Example (1 of 3)
#include <iostream.h>#include <stdlib.h>#include <time.h>#include <algorithm>
//QUICKSORT using an vector classinline double secs(clock_t c) { return (double)c/CLOCKS_PER_SEC;}
#define N 1000000int v[N];
5/8/2002 6
Array Example (2 of 3)
main(){ time_t c;
cout <<"\ntime start = " << secs(clock());
for (int i =0 ; i < N; ++i) v[i] = rand();
5/8/2002 7
Array Example (3 of 3)
//uses a quicksort algorithm
cout <<"\nstl sort start = " << secs(c = clock()); std::sort(v, v + N); cout <<"\n stl sort = " << secs( clock()-c); cout << endl;}
On my pentium 166 megahertz approx 2.8 secs for 1 million keys
On moondance 10 million keys approx 11 seconds
5/8/2002 8
Comments on Array
namespace std::sort() Used with ordinary vectors Speedy - compares to hand coded quick
sort Pointer values v and v + N
v is begin address v + N is end address (one past)
5/8/2002 9
Sequence - ordered by sequence of elements
Associative - keys for looking up elements
Both varieties share a similar interface
Two Varieties of Containers
vector list deque
set map multimapmultiset
5/8/2002 10
Typical Container Interfaces
Constructors default constructors, copy constructors
Element access Element insertion Element deletion Destructor Iterators
5/8/2002 11
Overview of Containers
Common set of properties Constructors and destructors Element access, insertion and deletion Allocate and manage memory
Associated allocator objects
5/8/2002 12
CAN() default constructorCAN(c) copy constructorc.begin() beginning location of CAN cc.end() ending location of CAN cc.rbegin() beginning for reverse iteratorc.rend() ending for reverse iteratorc.size() number of elements in CANc.max_size() largest possible sizec.empty() true if the CAN is emptyc.swap(d) swap two CANs
Container Members for CAN
5/8/2002 13
Container Operators
== != < > <= >=
5/8/2002 14
Typical Container Algorithm (1 of 2)
double sum(const deque<double> &lst){ double s = 0; deque<double>::const_iterator c;
for (c=lst.begin(); c != lst.end(); ++c) s += *c ; return s;}
5/8/2002 15
Typical Container Algorithm (2 of 2)
deque (double ended queue) container is traversed using a const_iterator
Iterator c is dereferenced to obtain each stored value in turn
Algorithm will work with all containers and all types that have operator+=() defined
5/8/2002 16
Containers with Iterators (1 of 2)
#include <iostream.h>#include <deque>using namespace std;
template<class itr> //common stl use of iteratordouble sum(itr b, itr e){ double s = 0.0; for( ; b != e; ++b) s = s + *b; return s;}
5/8/2002 17
Containers with Iterators (2 of 2)
//more general abstraction works on vectors//arrays indeed any container with iteratorint main(){ //initialize to 10 2.5's deque< double > data(10, 2.5); double d[5] = {1.0, 2.5, 3.3, 8.8, 9};
cout << sum(data.begin(), data.end()) << endl; cout << sum(d, d + 5)<< endl; cout << endl;}
5/8/2002 18
Comments on Containers with Iterators
Relies on use of iterator range Most standard idiom
Works with arrays as well using addresses Will be like an STL numeric algorithm Note use of constructor for initialization
5/8/2002 19
Associative Containers
Key based accessible elements
Ordering relation Compare Comparison object for the associative container
set map multimapmultiset
5/8/2002 20
Associative Container Program (1 of 2)
int main(){ map<string, int, less<string> > name_age;
//key, value stored, ordering name_age["Pohl,Laura"] = 7; name_age["Dolsberry,Betty"] = 39; cout << "Laura is " << name_age["Pohl,Laura"] << " years old." << endl;}
5/8/2002 21
Associative Container Program (2 of 2)
map name_age is an associative array where key is a string type
Compare object is less<string>
5/8/2002 22
ASSOC::key_type retrieval key type
ASSOC::key_compare comparison object
type
ASSOC::value_compare type for comparing ASSOC::value_type
Additional Associative Definitions
5/8/2002 23
c_unique.insert(t) Insert t, if no existing key tc_eq.insert(w_it, t) Insert t, return position w_itc.insert(w_it, t) Insert t with starting
position w_it for search (fails on sets and maps if key value already exists)
c(b_it, e_t) Inserts element rangec.erase(k) Erases elements with key
k,return # erased elementsc.erase(w_it) Erases pointed to elementc.erase(b_it, e_t) Erases range of elements
Associative Insert & Erase Functions (1 of 2)
5/8/2002 24
c.find(k) Returns iterator to element having key k, otherwise end
c.count(k) Returns # of elements with k
c.lower_bound(k) Returns iterator to first element having value greater than or equal to k
c.upper_bound(k) Returns iterator to first element having value greater than k
c.equal_range(k) Returns iterator pair for lower_bound & upper_bound
Associative Member Functions
5/8/2002 25
Modify existing containers to produce different public behaviors based on existing implementation
stack can be adapted from vector, list and deque
Last in first out data structureSupports back, push_back and pop_back
Container Adapter Classes
stack queue priority_queue
5/8/2002 26
void push(const value_type& v) Place v on stack
void pop() Remove top element
value_type& top() const Return top element
bool empty() const Returns true if stack empty
size_type size() const Returns # of elements
operator== and operator< Equality and less supported
Adapted Stack Functions
5/8/2002 27
Sequence Containers
Sequence containers have a sequence of accessible elements
C++ array type can also be treated as a sequence container
vector list deque
5/8/2002 28
Sequence Container Program (1 of 3)
//inserting a vector into a deque
int main(){ int data[5] = { 6, 8, 7, 6, 5 }; vector<int> v(5, 6); //5 element vect deque<int> d(data, data + 5); deque<int>::iterator dq_it;
5/8/2002 29
Sequence Container Program (2 of 3)
cout << "\n Deque values\n\n"; for (dq_it = d.begin(); dq_it != d.end(); ++dq_it) cout << *dq_it << '\t'; //print:6 8 7 6 5 cout << endl; d.insert(d.begin(), v.begin(), v.end()); for (dq_it = d.begin(); dq_it != d.end(); dq_it++) cout << *dq_it << '\t'; //print:6 6 6 6 6 6 8 7 6 5}
5/8/2002 30
Sequence Container Program (3 of 3)
5 element vector v initialized with value 6 deque d initialized with values taken from
array data insert() member function places v values in
specified range v.begin() to v.end() at location d.begin()
5/8/2002 31
SEQ::SEQ(n, v) n elements of value v
SEQ::SEQ(b_it, e_it) start at b_it and go to e_it - 1
c.insert(w_it, v) insert v before w_it
c.insert(w_it, v, n) insert n copies of v before w_it
c.insert(w_it, b_it, insert b_it to e_it e_it) before w_it
c.erase(w_it) erases element at w_it
c.erase(b_it, e_it) erase b_it to e_it
Additional Sequence Members in SEQ
5/8/2002 32
Adapted Containers (1 of 2)
Include Stack, Queue, Priority Queue Stack adapted from vector, list, or deque Stack adapted from user defined container
with operations empty, size, push_back, pop_back, and back operations stack < list < double > > stk
Supports stack operations
5/8/2002 33
Adapted Containers (2 of 2)
Queue adapted from list or deque but not vector needs push_back, pop_front
Priority queue can be adapted from vector or deque need random access
5/8/2002 34
Stack Adapted from Vector (1 of 2)
int main(){ stack<vector<string> > str_stack;
string quote[3] = {"The wheel that squeaks the loudest\n", "Is the one that gets the grease\n", "Josh Billings\n" };
5/8/2002 35
Stack Adapted from Vector (2 of 2)
for (int i =0; i < 3; ++i) str_stack.push(quote[i]);
while (!str_stack.empty()) { cout << str_stack.top(); str_stack.pop(); }}
5/8/2002 36
Iterators
Means for navigating data structure Iterators in STL are pointer-style objects
used to return with data stored in containers
Iterators in STL come in 5 categories
input
output
forward
bidirectional
random access
5/8/2002 37
Iterators and Containers and Algorithms
Algorithm may not support all iterator categories List will not support random access iterator but will
support bidirectional iterators
Sorting requires random access but finding requires only input iterator
Vector containers allow random access
5/8/2002 38
Input Iterator
Equality, dereferencing, autoincrement One pass algorithms read values in one direction
Conforms to following properties where Iter has first and first != last first++ //accesses next element
*first defined and can be used to compare, increment, dereference and assign elements of type Iter
Special case istream_iterator
5/8/2002 39
istream_iterator for Reading from Streams
int main(){ int d[5];
cout << "\nEnter integers: "; istream_iterator<int,ptrdiff_t> in(cin); for (int i = 0; i < 5; ++i) { d[i] = *in++; cout << "\nd[" << i << "] = " << d[i] << endl; }}
5/8/2002 40
Output Iterator
Supports dereferencing restricted to left hand side of assignment and autoincrement One pass algorithms write values in one direction
If Iter is output iterator type withIter ptr *ptr can be on the left hand side of assignment ptr++ is defined
5/8/2002 41
The output is all run together!
Special case ostream_iterator
Use the char* \t delimiter and a tab character will be issued to cout after each int value written
5/8/2002 42
The ostream_iterator for Writing to Streams
int main(){ int d[5] = {2, 3, 5, 7, 11}; //primes ostream_iterator<int> out(cout, "\t");
for (int i = 0; i < 5; ++i) *out = d[i] ;}
5/8/2002 43
Forward Iterator
Supports all input/ output operations Supports unrestricted use of assignment
Allows position within data structure retained from pass to pass
One directional multi-pass algorithms Able to save position and restart an
algorithm from that position
5/8/2002 44
Bidirectional Iterator
Supports all forward iterator operations
Supports both autoincrement and autodecrement General bidirectional multi-pass algorithms
5/8/2002 45
Random Access Iterators
Any location is accessible in constant time
5/8/2002 46
Random Access Iterators Support
All bidirectional operations General bidirectional multi-pass algorithms
Address arithmetic operations & comparison
ptr += n and ptr -= n ptr1 - ptr2
5/8/2002 47
STL Algorithms Library
Sorting algorithms Non-mutating sequence algorithms Mutating sequence algorithms Numerical algorithms Generally use iterators to access
containers instantiated on given type Resulting code can be competitive in efficiency with
special purpose codes
5/8/2002 48
Sorting Algorithms
General sorting, merge, heap, permutation, lexicographic comparison, binary search and selected other like operations
Algorithms have versions that use either operator<() or Compare object
5/8/2002 49
Using sort() for In-Memory quicksort
const int N = 5;
int main(){ int d[N], i, *e = d + N; for (i = 0; i < N; ++i) d[i] = rand(); sort(d, e); for (i = 0; i < N; ++i) cout << d[i] << '\t';}
5/8/2002 50
Sorting Algorithm Prototypes (1 of 6)
template<class RandAcc>void sort(RandAcc b, RandAcc e);
Quicksort algorithm over elements b to e
template<class RandAcc>void stable_sort(RandAcc b, RandAcc e);
Stable sorting algorithm over elements b to e Elements remain in their relative same position
5/8/2002 51
Sorting Algorithm Prototypes (2 of 6)
template<class RandAcc>void partial_sort(RandAcc b, RandAcc m, RandAcc e);
Partial sorting algorithm over elements b to e Only element b to m are sorted, remaining
elements are unsorted
5/8/2002 52
Sorting Algorithm Prototypes (3 of 6)
template<class InputIter, class RandAcc>void partial_sort_copy(InputIter b, InputIter e, RandAcc result_b, RandAcc result_e);
Partial sorting algorithm over elements b to e Elements are sorted taken from input iterator range
and copied to random access iterator range Smaller of two ranges is used
5/8/2002 53
Sorting Algorithm Prototypes (4 of 6)
template<class RandAcc>void nth_element(RandAcc b, RandAcc nth, RandAcc e);
The nth element is placed in sorted order If first position is parameter, then minimum element
found and placed in first position
5/8/2002 54
Sorting Algorithm Prototypes (5 of 6)
template<class InputIter1, class InputIter2, class OutputIter>OutputIter merge(InputIter1 b1, InputIter1 e1, InputIter2 b2, InputIter2 e2, OutputIter result_b);
Elements b1 to e1, and b2 to e2 are merged to starting position result_b
5/8/2002 55
Sorting Algorithm Prototypes (6 of 6)
template<class BidiIter>void inplace_merge(BidiIter b, BidiIter m, BidiIter e);
Elements b to m, and m to e are merged in place
5/8/2002 56
Sort Related Library Functions (1 of 5)
binary_search True if t is found in (b, e, t) b to e
upper_bound Last position for placing(b, e, t) t maintaining sort order
equal_range Returns iterator pair for(b, e, t) range where t placed,
maintaining sorted order
push_heap(b, e) Places last location’s element into existing
heap
5/8/2002 57
Sort Related Library Functions (2 of 5)
pop_heap(b, e) Places last location’selement into first location and reheaps remaining elements
sort_heap(b, e) Performs a sort on heap
make_heap(b, e) Creates a heap
next_permutation Produces next (b, e) permutation
5/8/2002 58
Sort Related Library Functions (3 of 5)
prev_permutation(b, e) Produces previous permutation
lexicographical_compare Returns true if(b1, e1, b2, e2) sequence 1 is
less than 2
min(t1, t2) Return minimum
max(t1, t2) Return maximum
5/8/2002 59
Sort Related Library Functions (4 of 5)
min_element(b, e) Return position of minimum
max_element(b, e) Return position of maximum
includes Returns true if (b1, e1, b2, e2) 2nd sequence is
subset of first
set_union Returns union as (b1, e1, b2, e2) output iterator
5/8/2002 60
Sort Related Library Functions (5 of 5)
set_intersection Returns set (b1, e1, b2, e2) intersection as an
output iteratorset_difference Returns set
difference (b1, e1, b2, e2)as output iterator
set_symmetric_ Returns set difference symmetric difference (b1, e1, b2, e2) as output iterator
5/8/2002 61
Sort Algorithms and Ordering with comp ()
Use a Compare object replacing operator<()
template<class RandAcc, class Compare>void sort(RandAcc b, RandAcc e, Compare comp);
Quicksort algorithm over elements b to e using comp for ordering
5/8/2002 62
Non-Mutating Sequence Algorithms
Do not modify contents of the containers they work on
Typical operation is searching container for particular element and returning its position
5/8/2002 63
Non-mutating find() For Locating element t
int main() // find pos of "hop"{ string words[5] = { "my", "hop", "mop", "hope", "cope"}; string* where;
where = find(words, words + 5, "hop"); cout << *++where << endl; //mop sort(words, words + 5); where = find(words, words + 5, "hop"); cout << *++where << endl; //hope}
5/8/2002 64
Non-mutating Algorithm Prototypes (1 of 2)
template<class InputIter, Class T>InputIter find(InputIter b, InputIter e, const T& t)); Finds position of t in range b to e
template<class InputIter, Class Predicate>InputIter find(InputIter b, InputIter e, Predicate p));
Finds position of first element that makes predicate true in range b to e, otherwise position e returned
5/8/2002 65
Non-mutating Algorithm Prototypes (2 of 2)
template<class InputIter, Class Function>void for_each(InputIter b, InputIter e, Function f)); Function f to each value found in range b to
e
5/8/2002 66
Non-Mutating Sequence Functions (1 of 5)
next_permutation Produces next( b, e)
prev_permutation Produces previous(b, e)
count(b, e, t, n) Returns to n count of elements equal to t
count_if(b, e, p, n) Returns to n count of elements that make
predicate p true
5/8/2002 67
Non-Mutating Sequence Functions (2 of 5)
adjacent_find(b, e) Returns first position of adjacent equal elements, otherwise e
adjacent_find Returns first position (b, e, binp) of adjacent elements satisfying binary predicate binp, otherwise e
5/8/2002 68
Non-Mutating Sequence Functions (3 of 5)
mismatch(b1, e1, b2) Returns iterator pair indicating positions where elements
don’t match from given sequences starting with b1 and b2
mismatch As above with (b1, e1, b2, binp) binary predicate
binp used instead of
equality
5/8/2002 69
Non-Mutating Sequence Functions (4 of 5)
equal(b1, e1, b2) Returns true if indicated
sequences match, otherwise false
equal As above with binary (b1, e1, b2, binp) predicate binp used instead of equality
5/8/2002 70
Non-Mutating Sequence Functions (5 of 5)
search(b1, e1, b2, e2) Return iterator where 2nd sequence contained in
first, and if not e1
search As above with (b1, e1, b2, e2, binp) binary predicate binp used instead of equality
5/8/2002 71
Mutating Sequence Algorithms
Modify contents of containers they work on
Reversing the contents of a container
5/8/2002 72
Mutating reverse() & copy() Program (1 of 3)
int main(){ string first_names[5] = {"laura", "ira", "buzz", "debra", "twinkle"}; string last_names[5] = {"pohl", "pohl", "dolsberry", "dolsberry", "star"}; vector<string> names(first_names, first_names + 5); vector<string> names2(10); vector<string>::iterator p;
5/8/2002 73
Mutating reverse() & copy() Program (2 of 3)
copy(last_names, last_names + 5, names2.begin()); copy(names.begin(), names.end(), names2.begin() + 5); reverse(names2.begin(), names2.end()); for (p = names2.begin(); p != names2.end(); ++p) cout << *p <<'\t';}
5/8/2002 74
Mutating reverse() & copy() Program (3 of 3)
First invocation of mutating copy() places last_names in the container vector names2
Second call to copy() copies in first_names which had been used in construction of vector names
reverse() reverses all elements which are then printed out
5/8/2002 75
Mutating Function Prototypes (1 of 5)
template<class InputIter, class OutputIter>OutputIter copy(InputIter b1, InputIter e1, OutputIter b2); Copying algorithm over elements b1 to e1
Copy is placed starting at b2 Position returned is end of copy
5/8/2002 76
Mutating Function Prototypes (2 of 5)
template<class BidiIter1, class BidiIter2>BidiIter2 copy_backward(BidiIter1 b1, BidiIter1 e1, BidiIter2 b2);
Copying algorithm over elements b1 to e1 Copy is placed starting at b2 Copying runs backward from e1 into b2 also going
backwards Position returned is b2 - (e1 - b1)
5/8/2002 77
Mutating Function Prototypes (3 of 5)
template<class BidiIter>void BidiIter(BidiIter b, BidiIter e);
Reverses in place elements b to e
template<class BidiIter, class OutputIter>OutputIter reverse_copy(BidiIter b1, BidiIter e1, OutputIter b2);
Reverse copy on elements b1 to e1 Copy in reverse is placed starting at b2 Copying runs backward from e1 into b2 also going backwards Position returned is b2 + (e1 - b1)
5/8/2002 78
Mutating Function Prototypes (4 of 5)
template<class ForwIter>ForwardIter unique(ForwIter b, ForwIter e);
Adjacent elements in range b to e erased Position returned is end of resulting range
template<class ForwIter, class BinaryPred>ForwardIter unique(ForwIter b, ForwIter e, BinaryPred bp);
Adjacent elements in range b to e with binary predicate bp satisfied erased Position returned is end of resulting range
5/8/2002 79
Mutating Function Prototypes (5 of 5)
template<class InputIter, class OutputIter>OutputIter unique_copy(InputIter b1, InputIter e1, OutputIter b2);
template<class InputIter, class OutputIter, class BinaryPred>OutputIter unique_copy(InputIter b1, InputIter e1, OutputIter b2, BinaryPred bp); Results copied to b2 with original range
unchanged
5/8/2002 80
Numerical Algorithms
Sums Inner product Adjacent difference Numerical Algorithm functions behave as
expected on numerical types where + and * are defined
5/8/2002 81
Numerical Algorithm Program
int main(){ double v1[3] = { 1.0, 2.5, 4.6 }, v2[3] = { 1.0, 2.0, -3.5 }; double sum, inner_p;
sum = accumulate(v1, v1 + 3, 0.0); inner_p = inner_product(v1, v1 + 3, v2, 0.0); cout << "sum = " << sum << ", product = " << inner_p << endl;}
5/8/2002 82
Numerical Algorithm Prototypes (1 of 2)
template<class InputIter, class T>T accumulate(InputIter b, InputIter e, T t); Standard accumulation algorithm whose
sum is initially t Successive elements from the range b to e are
added to sum
5/8/2002 83
Numerical Algorithm Prototypes (2 of 2)
template<class InputIter, class T, class BinOp>T accumulate(InputIter b, InputIter e, T t, BinOp bop); Accumulation whose sum is initially t
Successive elements from range b to e are summed with sum = bop(sum, element)
5/8/2002 84
Numerical Algorithm Functions (1 of 3)
inner_product(b1, e1, b2 ,t)
Returns inner product from two ranges starting with b1 and b2 Product is initialized to t which is usually 0
inner_product(b1, e1, b2, t, bop1, bop2)
Returns generalized inner product using bop1 to sum and bop2 to multiply
5/8/2002 85
Numerical Algorithm Functions (2 of 3)
partial_sum(b1, e1, b2)
Produces sequence starting at b2, that is partial sum of terms from range b1 to e1
partial_sum(b1, e1, b2, bop)
As above using bop for summation
5/8/2002 86
Numerical Algorithm Functions (3 of 3)
adjacent_difference(b1, e1, b2)
Produces sequence starting at b2, that is adjacent difference of terms from b1 to e1
adjacent_difference(b1, e1, b2, bop)
As above using bop for difference
5/8/2002 87
Function Objects
Useful to have function objects to further leverage STL library Numerical functions have built-in meaning using +
or *, as well as user-provided binary operators which could be passed in
Defined function objects can be found in function.h or built
Function objects are classes that have operator() defined Inlined, compiled producing efficient object code
5/8/2002 88
Function Object for minus<int>
int main(){ double v1[3] = {1.0, 2.5, 4.6}, sum;
sum = accumulate(v1, v1 + 3, 0.0, minus<int>()); cout << "sum = " << sum << endl; //sum = -7} Accumulation using integer minus for
binary operation over the array v1[]
5/8/2002 89
Defined Function Object Classes
Arithmetic objects
Comparison objects
Logical objects
5/8/2002 90
Arithmetic Objects (1 of 2)
template <class T>struct plus<T>
Adds two operands of type T
template <class T>struct minus<T> Subtracts two operands of type T
template <class T>struct times<T>
Multiplies two operands of type T
5/8/2002 91
Arithmetic Objects (2 of 2)
template <class T>struct divides<T>
Divides two operands of type T
template <class T>struct modulus<T>
Modulus (%) for two operands of type T
template <class T>struct negate<T>
Unary minus for one argument of type T
5/8/2002 92
Comparison Objects (1 of 2)
template <class T>struct equal_to<T>
Equality of two operands of type T
template <class T>struct not_equal_to<T>
Inequality of two operands of type T
template <class T>struct greater<T>
Comparison by greater (>) of two operands of type T
5/8/2002 93
Comparison Objects (2 of 2)template <class T>struct less<T> Comparison by less of two operands of type T
template <class T>struct greater_equal<T> Comparison by greater or equal (>=) of two
operands of type T
template <class T>struct less_equal<T> Comparison by less or equal (<=) of two
operands of type T
5/8/2002 94
Logical Objects
template <class T>struct logical_and<T>
Logical and (&&) on 2 operands of type T
template <class T>struct logical_or<T>
Logical or (||) on 2 operands of type T
template <class T>struct logical_not<T>
Logical negation (!) on 1argument of type T
5/8/2002 95
Function Adapters
Creation of function objects using adaption Negators for negating predicate objects Binders for binding a function argument Adapters for pointer to function
5/8/2002 96
Use of Function Adapter bind2nd (1 of 2)
template <class ForwIter>void print(ForwIter first, ForwIter last, const char* title){ cout << title << endl; while( first != last) cout << *first++ << '\t'; cout << endl;}
5/8/2002 97
Use of Function Adapter bind2nd (2 of 2)
// use a binder function bind2nd to transform initial sequence of values to these values doubledint main(){ int data[3] = { 9, 10, 11};
print(data, data + 3, "Original values"); transform(data, data + 3, data, bind2nd(times<int>(), 2)); print(data, data + 3, "New values");}
5/8/2002 98
Function Adapters (1 of 3)
template<class Pred> unary_negate<Pred> not1(const Pred& p)
Returns !p where p is a unary predicate
template<class Pred>binary_negate<Pred> not2(const Pred& p)
Returns !p where p is a binary predicate
5/8/2002 99
Function Adapters (2 of 3)
template<class Op, class T>binder1st<Op>bind1st(const Op& op, const T& t)
Binary op has first argument bound to t Function object is returned
template<class Op, class T>binder2nd<Op>bind2nd(const Op& op, const T& t)
Binary op has 2nd argument bound to t function object is returned
5/8/2002 100
Function Adapters (3 of 3)
template<class Arg, class T>ptr_fun(T (*f)(Arg))
Constructs pointer_to_unary_function<Arg, T>
template<class Arg1, class Arg2, class T>ptr_fun(T (*f)(Arg1, Arg2))
Constructs pointer_to_binary_function<Arg,T>
5/8/2002 101
STL Based on Templates
Key to understanding STL is to use iterator
logic
When extending STL keep consistent with
existing libraries
Generality and genericity are not
enough.Its not STL if it isn’t efficient