Overview of STL Function Objects

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Chapter 14 Operator Overloading: What does + mean? Consider the code below. Note the multiple uses of “+”. #include using namespace std; int main() { int.
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.
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.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
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: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
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 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
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: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Containers Overview and Class Vector
Programming Languages and Paradigms Object-Oriented Programming (Part II)
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)‏
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.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
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:
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
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.
Overview of C++ Templates
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
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
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Overview of C++ Polymorphism
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
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.
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)
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
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.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
C++ Functions A bit of review (things we’ve covered so far)
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
The C++ Algorithm Libraries
ADT Implementations: Templates and Standard Containers
Overview of C++ Polymorphism
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

Overview of STL Function Objects Function Object (also known as a Functor) STL Function Objects support function call syntax E.g., a class that declares and defines operator() E.g., by being a function pointer GoF Command pattern may be applied to classes and structs (user-defined types) Encapsulate a function call as an object Some or all of these can be member variables Target object reference, function to invoke, arguments Generic programming allows diverse types A function pointer (example from Lippman, LaJoie, Moo) bool (*pf) (const string &, const & string) // function pointer bool *pf (const string &, const & string) // function named pf An instance of a class providing operator()

Function Objects Extend STL Algorithms Make the algorithms even more general Can be used parameterize policy E.g., the order produced by a sorting algorithm Each functor does a single, specific operation Often implemented as small classes or structs Often has only one public member function, operator() Functors 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 +k functor E.g., arguments for an invocation on a remote object

Examples of Function Object Usage struct GT_magnitude : public binary_function<double, double, bool> { bool operator() (double x, double y) { return fabs(y) < fabs(x); } }; struct LT_magnitude fabs(x) < fabs(y); int main (int, char **) { vector<double> 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<double> o (cout, “ ”)); copy (u.begin(), u.end(), o); copy (v.begin(), v.end(), o); return 0;

Function Object Concepts Basic Function Object Concepts Generator Unary Function Binary Function Adaptable Function Objects (turn functions into functors) 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

Function Object Concept Hierarchy Assignable is-refined-by Generator Binary Function Unary Function Adaptable Generator Binary Predicate Adaptable Binary Function Random Number Generator Predicate Adaptable Unary Function Adaptable Predicate Hash Function Adaptable Binary Predicate Strict Weak Ordering Basic Function Object Predicate Specialized Adaptable Function Object

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 Here, all Basic Function Object concepts Generator, Unary Function, Binary Function And the concepts that specialize them

Generator Concept Refines Assignable Abstracts 0-ary functions (take 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

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

Unary Function Also a refinement of Assignable Valid Expression Function call signature with one argument f(x) Semantics May ignore or use single argument Similar return, const semantics to generator Example - Unary Sine Functor struct sine : public unary_function<double,double> { double operator()(double x) const { return sin(x); } };

Binary Function Also a refinement of Assignable Valid Expression Function call signature with two arguments f(x,y) Semantics May use or ignore either or both of its arguments Similar const and return semantics to Unary Function Example - Exponentiation Functor struct exponentiate : public binary_function<double,double,double> { double operator()(double x, double y) const { return pow(x,y); } };

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 Functions like Result(*f)(Arg) are not models of these concepts Helper adapters make Adaptable Function Objects from these functions For example ptr_fun(f) is a model of Adaptable Unary Function

Adaptable Function Object Example Each value in v2 will be 3.0 larger than the corresponding element in v1 const int N = 1000; vector<double> v1(N); vector<double> v2(N); // random values generate(v1.begin(), v1.end(), rand); transform(v1.begin(), v1.end(), v2.begin(), bind1st(plus<double>(), 3.0)); Adaptable Function Object Function Object Adapter (we’ll cover these in a bit)

Predicate Concepts Predicate Adaptable Predicate Binary Predicate Refinement of Unary Function Return type must be convertible to bool Adaptable Predicate Refinement of Predicate, Adaptable Unary Function Adds typedefs 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 typedefs for the 2 arguments, return types Strict Weak Ordering Refinement of Binary Predicate (for comparison operations) Similar semantics to operator< but with type constraints

Random Number Generator Refinement of Unary Function Unfortunately name is similar to Generator (0-ary) Valid Expression Function call f(N), where N is a positive integer Semantics Returns some value of type Result Different invocations may return different values Normal pseudo-random distribution If function f is called many times with the same argument N then Each value in range [0,N) will appear ~ equal number of times

Hash Function Refinement of Unary Function Valid Expression Semantics Return type must be size_t Valid Expression Function call f(x) Semantics Map from argument to a size_t result Equivalent arguments must yield same result Used by Hashed Associative Containers

Function Object Adaptors Adaptors transform one interface to another I.e., they implement the Adapter pattern Function Object Adaptors Perform function composition and binding Allows fewer ad hoc function objects Allows you to build functions as graphs (especially chains and trees) of other functions

Composition and Binding with Function Objects Function Composition f and g are both Adaptable Unary Functions g return type is convertible to f argument type (f ◦ g)(x) which is f(g(x)) can be written using unary_compose<f,g> or compose1(f,g) Function Binding Adaptable Binary Function to Adaptable Unary Function Bind first argument using binder1st<BinaryFun> Where f is an object of type binder1st<F> f(x)  F(c,x) where c is constant Bind second argument using binder2nd<BinaryFun> Where f is an object of type binder2nd<F> f(x)  F(x,c) where c is constant

Example of Function Composition Calculate negative of sine of angles in degrees Performed as a sequence of three operations Conversion of degrees to radians Calculation of sine Negation vector<double> angles; // ... push in some radian values ... vector<double> sines; const double pi = 3.14159265358979323846; transform(angles.begin(), angles.end(), sines.begin(), compose1(negate<double>(), compose1(ptr_fun(sin), bind2nd(multiplies<double>(), pi / 180.0))));

Example of Explicit Call Chains Carry out operations in some specified order template <class R, class List> class Chain { Fun2& operator()(const Fun1<R, List>& fun1, const Fun2<R, List>& fun2) { fun1(); return fun2(); } };

Member Function Adaptors Allows use of member functions as Function Objects Similar adaptors available for non-member functions Take an X* or X& argument and call one of the X object’s member functions through that argument If the member function is virtual, call is polymorphic Three variations Argument type X* vs. X& Member Function takes zero vs. one argument Encapsulates non-const vs. const member function

Member Function Adaptor Example 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 **) { vector<B*> v; v.push_back(new D1); v.push_back(new D2); v.push_back(new D2); v.push_back(new D1); for_each(v.begin(), v.end(), mem_fun(& B::print)); return 0; }

Concluding Remarks Passing parameters to Functors Can do by value or by reference Same kinds of aliasing issues, etc. as with any other object Watch performance with many small function objects Watch out especially for creation, destruction overhead May want to inline functors constructors, destructors Put function objects on stack instead of heap Function objects are a powerful, general mechanism Reduces programming complexity, increases reuse Several new uses of generic programming Could go farther with parameterization than just algorithms Use functors to make smarter iterators and containers

Topic: C++ STL Case Study For Next Time Topic: C++ STL Case Study An example of using (mostly) the STL to program and thus do something useful more easily How it all fits together algorithms, iterators, containers, and function objects A short presentation on the Lab 6 assignment No assigned reading for next time But it’s a good time to catch up, if needed