CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Chapter 14: Overloading and Templates
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
CSE 332: Course Review CSE 332 Course Review Review session goals –Survey and summarize the semester’s material A chance to clarify/review ideas/examples,
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
C++ Review (3) Structs, Classes, Data Abstraction.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Chapter 8 Operator Overloading, Friends, and References.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Object-Oriented Programming in C++ More examples of Association.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 Introduction to Object Oriented Programming Chapter 10.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
2/26/ Customization Points and Polymorphism Functional Programming Boost.Lambda.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Overview of STL Function Objects
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
COMP 3000 Object-Oriented Programming for Engineers and Scientists Operator Overloading Dr. Xiao Qin Auburn University
Washington WASHINGTON UNIVERSITY IN ST LOUIS More on the STL: Function Objects and Generic Algorithms in the STL Fred Kuhns Computer Science and Engineering.
Motivation for Generic Programming in C++
“Generic Programming” ECE 297
Pointers and Dynamic Arrays
Standard Template Library
STL – Standard Template Library
The C++ Algorithm Libraries
C++ Functions, Classes, and Templates
Lists - I The List ADT.
Lists - I The List ADT.
C++ Templates L03 - Iterator 10 – Iterator.
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators –E.g., calling operator< during a sort algorithm –Those expressions define type requirements –In many cases, can plug in alternative behaviors The STL allows diverse functor types –A function pointer (from Lippman, LaJoie, Moo) bool (*PF) (const string &, const string &); // function pointer bool pf (const string &, const string &); // function –Instance of a class/struct providing operator() –Either one can be invoked (called) But may have to deal with signature (and return type)

CSE 332: C++ STL functors STL Functors Extend STL Algorithms Make the algorithms/containers even more general Can be used parameterize policy –E.g., the order produced by a sorting algorithm –E.g., the order maintained by an associative container Each functor does a single, specific operation –Often implemented as small functions or classes/structs E.g., a struct with one public member function, operator() Function objects may also have member variables –Arguments not stored may be supplied at point of call –Member variables can parameterize the operation –E.g., the value k for a functor that adds k to another value –E.g., arguments for an invocation on a remote object

CSE 332: C++ STL functors Function Object Use in an Algorithm struct GT_magnitude : public binary_function<double, double, bool> { bool operator() (double x, double y) { return fabs(y) < fabs(x); } }; struct LT_magnitude : public binary_function<double, double, bool> { bool operator() (double x, double y) { return fabs(x) < fabs(y); } }; int main (int, char **) { vector u,v; for (double d = 0.0; d < 10.1; d += 1.0){ u.push_back (d); v.push_back (d); } sort (u.begin(), u.end(), GT_magnitude()); sort (v.begin(), v.end(), LT_magnitude()); ostream_iterator o (cout, “ ”); copy (u.begin(), u.end(), o); copy (v.begin(), v.end(), o); return 0; }

CSE 332: C++ STL functors Function Use in an Algorithm #include using namespace std; struct Employee { Employee (const char * n, int i) : name_(n), id_(i) {} string name_; int id_; }; typedef Employee * EmployeePtr; ostream& operator<< (ostream & os, const EmployeePtr & e) { os name_ id_ << " "; return os; } // function for comparing EmployeePtrs bool id_compare (const EmployeePtr & e, const EmployeePtr & f) { return e->id_ id_|| (e->id_ == f->id_ && e->name_ name_); } int main (int, char *[]) { vector v; v.push_back(new Employee("Claire", 23451)); v.push_back(new Employee("Bob", 12345)); v.push_back(new Employee("Alice", 54321)); cout << "v: " ; copy (v.begin(), v.end(), ostream_iterator (cout)); cout << endl; // "v: Claire Bob Alice " sort (v.begin(), v.end(), id_compare); cout << "v: " ; copy (v.begin(), v.end(), ostream_iterator (cout)); cout << endl; // "v: Bob Claire Alice " // clean up: pointers "own" the heap objects for (vector ::iterator i = v.begin(); i != v.end(); ++i) { delete *i; } return 0; } function name ok here heap object

CSE 332: C++ STL functors Function Object Use in a Container #include using namespace std; struct Employee { Employee (const char * n, int i) : name_(n), id_(i) {} string name_; int id_; }; ostream& operator<< (ostream & os, const Employee & e) { os << e.name_ << " " << e.id_ << “ "; return os; } // set needs this (orders by name then id) bool operator< (const Employee & e, const Employee & f) { return e.name_ < f.name_ || (e.name_ == f.name_ && e.id_ < f.id_); } // orders by id then name) struct EmployeeIdComp { bool operator() (const Employee & e, const Employee & f) { return e.id_ < f.id_ || (e.id_ == f.id_ && e.name_ < f.name_); } }; int main (int, char *[]) { vector v; v.push_back(Employee("Claire", 23451)); v.push_back(Employee("Bob", 12345)); v.push_back(Employee("Alice", 54321)); cout << "v: " ; copy (v.begin(), v.end(), ostream_iterator (cout)); // "v: Claire Bob Alice " set s; s.insert(v.begin(), v.end()); cout << "s: " ; copy (s.begin(), s.end(), ostream_iterator (cout)); // "s: Alice Bob Claire “ set t; t.insert(v.begin(), v.end()); cout << "t: " ; copy (t.begin(), t.end(), ostream_iterator (cout)); // "t: Bob Claire Alice “ return 0; } function object needed temporary object

CSE 332: C++ STL functors STL Before and After C++11 Parts were deprecated in C++11, but are still available in Visual C –E.g., inherit from unary_function and binary_function to decorate a callable object with associated types reflecting its function call signature –E.g., make a functor for a member function call through a pointer using mem_fun –E.g., make a functor for a member function call through a reference using mem_fun_ref –E.g., bind first argument using binder1st –E.g., bind second argument using binder2nd –See for more details New versions introduced in C++11, are also available in Visual C –E.g., bind any argument using bind and _1 _2 _3 etc. –E.g., make a functor for a member function call through pointer or reference using mem_fn –E.g., wrap a callable object with a function call signature using function –New versions provide similar capabilities, but are more consistent and general than before –Availability may depend on compiler version, older code may involve previous versions –See for more details

CSE 332: C++ STL functors Pre-C++11 Member Function Adaptor Example // Based on the SGI C++ STL page examples struct B { virtual void print() = 0; }; struct D1 : public B {void print() {cout<<"I'm a D1"<< endl;}}; struct D2 : public B {void print() {cout<<"I'm a D2"<< endl;}}; int main(int, char **) { D1 d1; D2 d2; vector v; vector w; v.push_back(&d1); v.push_back(&d2); v.push_back(&d2); v.push_back(&d1); w.push_back(d2); for_each(v.begin(), v.end(), mem_fun(& B::print)); cout << endl << endl; for_each(w.begin(), w.end(), mem_fun_ref(& B::print)); return 0; } different wrappers needed

CSE 332: C++ STL functors C++11 Member Function Adaptor Example // Previous example modified to use mem_fn in both cases struct B { virtual void print() = 0; }; struct D1 : public B {void print() {cout<<"I'm a D1"<< endl;}}; struct D2 : public B {void print() {cout<<"I'm a D2"<< endl;}}; int main(int, char **) { D1 d1; D2 d2; vector v; vector w; v.push_back(&d1); v.push_back(&d2); v.push_back(&d2); v.push_back(&d1); w.push_back(d2); for_each(v.begin(), v.end(), mem_fn(& B::print)); cout << endl << endl; for_each(w.begin(), w.end(), mem_fn(& B::print)); return 0; } same wrapper for both

CSE 332: C++ STL functors STL Functor Concepts Basic Functor Concepts –Generator –Unary Function –Binary Function Adaptable Function Objects (turn functions into function objects) –Adaptable Generator –Adaptable Unary Function –Adaptable Binary Function Predicates (return a boolean result) –Predicate –Binary Predicate –Adaptable Predicate –Adaptable Binary Predicate –Strict Weak Ordering Specialized Concepts –Random Number Generator –Hash Function

CSE 332: C++ STL functors STL Functor Concept Hierarchy Adaptable Function Object Basic Function Object Specialized Predicate is-refined-by Generator Unary Function Binary Function Assignable Adaptable Generator Adaptable Unary Function Adaptable Binary Function Hash Function Random Number Generator Predicate Adaptable Predicate Binary Predicate Adaptable Binary Predicate Strict Weak Ordering

CSE 332: C++ STL functors Assignable Concept Does not refine any other STL concept Valid Expressions –Copy Constructor X(x); X x(y); X x = y; –Assignment x = y; Models of Assignable –Almost every non-const C++ built-in type … –… and function pointers … –… but not functions (cannot construct or assign them) –Here, all Basic Function Object concepts Generator, Unary Function, Binary Function And the concepts that specialize them

CSE 332: C++ STL functors Generator Concept Refines Assignable Abstracts pointers to 0-ary functions (no arguments) Valid Expressions –Function call signature with no arguments f() Semantics –Returns some value of type Result –Different invocations may return different values Or, can represent a constant as a 0-ary functor –Invocation may change the function object’s internal state So, operator() need not be a const member function

CSE 332: C++ STL functors Generator Example Goal: fill a vector with random numbers Generic generate algorithm –Fills in a range given in its 1 st and 2 nd arguments –applies Generator Concept to its 3 rd argument Here, the functor is simply a function pointer –To the (0-ary) rand() function vector v(100); generate(v.begin(), v.end(), rand);

CSE 332: C++ STL functors Unary Function Concept Also a refinement of Assignable Valid Expression –Function call signature with one argument f(x) –May ignore or use single argument –Similar return, const semantics to generator Pre-C++11 Example using unary_function struct sine : public unary_function { double operator()(double x) const { return sin(x); } }; sine func; C++11 Example using function function func(sin);

CSE 332: C++ STL functors Binary Function Concept Also a refinement of Assignable Valid Expression –Function call signature with two arguments f(x,y) –May use or ignore either or both of its arguments –Similar const and return semantics to Unary Function Pre-C++11 Example using binary_function struct exponentiate : public binary_function { double operator()(double x, double y) const { return pow(x,y); } }; C++11 Example using function function func(pow);

CSE 332: C++ STL functors Adaptable Function Objects Allow functors to be used with Function Object Adaptors Associated types – of argument(s), and especially return value How to access these associated types ? –Define Adaptable Function Object Concepts Adaptable Generator F1::result_type Adaptable Unary Function F2::argument_type F2::result_type Adaptable Binary Function F3::first_argument_type F3::second_argument_type F3::result_type Models –Function pointers like Result(*f)(Arg) do not model these concepts –Helper adapters make Adaptable Function Objects from these functions Pre-C++11 ptr_fun(f) or C++11 function (f)

CSE 332: C++ STL functors Adaptable Function Object Example Each value printed out will be 3.0 larger than the corresponding element in v1 int main(int, char **) { const int vector_size = 10; vector v1(vector_size); generate(v1.begin(), v1.end(), rand); // random values transform(v1.begin(), v1.end(), ostream_iterator (cout, " "), bind1st(plus (), 3.0)); transform(v1.begin(), v1.end(), ostream_iterator (cout, " "), std::bind(plus (), std::placeholders::_1, 3.0)); return 0; } C++11 function adapter Adaptable function objects Pre-C++11 function adapter

CSE 332: C++ STL functors Predicate Concepts Predicate –Refinement of Unary Function –Return type must be convertible to bool Adaptable Predicate –Refinement of Predicate, Adaptable Unary Function –Adds typedef s for argument, return types Binary Predicate –Refinement of Binary Function –Return type again must be convertible to bool Adaptable Binary Predicate –Refinement of Binary Predicate, Adaptable Binary Function –Adds typedef s for the 2 arguments, return types Strict Weak Ordering –Refinement of Binary Predicate (for comparison operations) –Similar semantics to operator< but with type constraints