CS212: Object Oriented Analysis and Design Lecture 28: Functors.

Slides:



Advertisements
Similar presentations
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Advertisements

C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
1 Iterators & Algorithms Iterators provide a link between containers and algorithms Example: We wish to write a function sum() that adds up the members.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Stacks Stack Examples Stack API More Examples/Uses Base Conversion Activation Records RPN Implementing a Stack Stacks.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
STL Algorithms algorithms independent of containers.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
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)‏
The C++ Standard Template Library. What is STL A subset of the standard C++ library –The string class is not part of it! 3 major components –Algorithms.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
CSCE 121: Introduction to Program Design and Concepts, Honors J. Michael Moore Spring 2015 Set 19: The STL: Containers and Iterators 1.
Lecture 17 Templates, Part I. What is a Template? In short, it’s a way to define generic functionality on parameters without needing to declare their.
Generic Programming in C++. Generic Parameters Function for squaring a number: Function for squaring a number: sqrt(x) { return x * x; } C version: C.
CSC Data Structures, Fall, 2008 Monday, September 29, end of week 5, Generic Functions and Classes in C++
1 Iterators Good reference site:
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Writing Generic Functions Lecture 20 Hartmut Kaiser
Overview of C++ Templates
Intro to the C++ STL Timmie Smith September 6, 2001.
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
Programming in C++ Michal Brabec Petr Malý. Class / Struct Class / Struct consists of: data members function members constructors destructor copy constructor.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
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)
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
Chapter 8 Writing Generic Functions. Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Overview of STL Function Objects
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Generic Programming in C++ Giuseppe Attardi Università di Pisa.
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++
CS212: Object Oriented Analysis and Design
Standard Template Library
Templates.
18 – Sequential Containers
C++ STL Vector Container
CS212: Object Oriented Analysis and Design
CMSC 202 Lesson 22 Templates I.
Lists - I The List ADT.
Lists - I The List ADT.
Templates I CMSC 202.
Standard Template Library
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
Jim Fawcett CSE687 – Object Oriented Design Spring 2002
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
C++ Templates L04 - Iterator 10 – Iterator.
Standard Template Library
Presentation transcript:

CS212: Object Oriented Analysis and Design Lecture 28: Functors

Recap of Lecture 27 STL Algorithms Accumulate Reordering algorithms Searching algorithm Removing algorithm

Outline of Lecture 28 Adapters Predicate functions Function Objects

Iterator Adaptors Source Target Source Target Before copy After copy copy(start, stop, result)

Iterator Adaptors Iterator adaptors are defined in the header They are objects that act like iterators Don't actually point to elements of a container e.g. ostream_iterator

A closer look at ostream_iterator They are parameterized We passed it two pieces of information 1.A stream to write to, in this case cout 2.A separator string Demonstration (Iter_Adapt.cpp) ostream_iterator myItr(cout, " " ); vector ::iterator it;

ostream_iterator Iterator adaptors are iterators, and so they can be used in conjunction with the STL algorithms Supply an iterator adaptor instead to “trick” the algorithm Performing some complex task when it believes it's just writing values to a range copy(myVector.begin(), myVector.end(), ostream_iterator (cout, " "));

Common Iterator adapter NameExample back_insert_iterator back_insert_iterator > itr(myVector); front_insert_iterator front_insert_iterator > itr(myIntDeque); insert_iterator insert_iterator > itr( mySet, mySet.begin()); ostream_iterator ostream_iterator itr( myStream, "\n"); istream_iterator istream_iterator itr(cin);

A Word on Compatibility STL implementations are uniform C++ code that works on one compiler should work on any other compile Unfortunately, this is not the case string ConvertToLowerCase(string text) { transform (text.begin(), text.end(), text.begin(), tolower ); return text; }

Predicate functions Many of the STL generic algorithms take a functional argument template T accumulate (InputIterator first, InputIterator last, T init); template T accumulate( InputIt first, InputIt last, T init, BinaryOperation op ); Second version uses a given binary function The signature of the function should be equivalent to the following: Ret fun(const Type1 &a, const Type2 &b); Demonstration (AccumCustom.cpp, SortCustom.cpp)

Common binary predicates equal_to(){ if (arg1 == arg2) return TRUE; else return FALSE; } not_equal_to() greater() less() greater_equal() less_equal() logical_and() logical_or()

Common arithmetic functions plus(){ return ( arg1 + arg2); } minus(){ return ( arg1 - arg2 ); } multiplies(){ return ( arg1 * arg2 ); } divides(){ return ( arg1 / arg2 ); } modulus(){ return ( arg1 % arg2 ); }

Function Objects string mystr[] = {“Me”,”You”,”He”,”She”,”You”,”They”}; int mycount = count (mystr, myints+6, “You”); The function uses operator == to compare the individual elements to val. Count the number of string s that have length greater than 3 int numEvens = count_if(myVector.begin(), myVector.end(), LengthIsLessThanThree); bool LengthIsLessThanThree(const string& str) { return str.length() < 3; }

Alternative design A function has access the following information: Its local variables. Its parameters. Global variables. This is not an optimal solution It is error-prone, It is not scalable, It uses global variables bool LengthIsLessThanThree(const string& str, size_t length) { return str.length() < length; } Should be unary

Functors to rescue Issue: Unary function does not have access to enough information Intension: A unary function to act like a binary function without taking an extra parameter A functor (or function object) is an C++ class that acts like a function Can be accessed like objects, but behaves like functions MyClass myFunctor; cout << myFunctor(137) << endl;

More on functor signature Create an object that overloads the function call operator, operator () It is a function called operator (), not a function called operator that takes no parameters Defining a function that gets called if we invoke the object like a function cout << myFunctor(137) << endl; is equivalent to cout << myFunctor.operator()(137) << endl;

The operator() Return an object of any type (or even void) Can accept any number of parameters class MyFunctor { public: void operator() (const string& str) const { cout << str << endl; } };

Functions vs Functors A functor's function call operator is a member function A raw C++ function is a free function A function has access to Its local variables. Its parameters. Global variables. A functor has access to Its local variables. Its parameters. Global variables. Class data members.

count_if revisited int numEvens = count_if(myVector.begin(), myVector.end(), LengthIsLessThanThree); class ShorterThan { private: const size_t length; public: ShorterThan(size_t maxLength) : length(maxLength) {} bool operator() (const string& str) const { return str.length() < length; } }; count_if(myVector.begin(), myVector.end(), ShorterThan(length));

Function with local state Those local variables can be very useful Suppose you wanted to look at a container of XY coordinates and find the one closest to some point P. template ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp );

Thank you Next Lecture: Functors