Washington WASHINGTON UNIVERSITY IN ST LOUIS More on the STL: Function Objects and Generic Algorithms in the STL Fred Kuhns Computer Science and Engineering.

Slides:



Advertisements
Similar presentations
Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
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.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
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++ 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.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Higher order programming Using C++ and boost. C++ concepts // T must model MyFuncConcept template generic_function(T t) { t.MyFunc(); }
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
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)‏
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
CSCE 121: Introduction to Program Design and Concepts, Honors J. Michael Moore Spring 2015 Set 19: The STL: Containers and Iterators 1.
Generic Programming in C++. Generic Parameters Function for squaring a number: Function for squaring a number: sqrt(x) { return x * x; } C version: C.
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++ 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.
Overview of C++ Templates
Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.
Moshe Fresko Bar-Ilan University Object Oriented Programming
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
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 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
Overview of STL Function Objects
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
C++ REVIEW – TEMPLATES. GENERIC PROGRAMMING Programming/developing algorithms with the abstraction of types Algorithms/data is expressed “without type”
Generic Programming in C++ Giuseppe Attardi Università di Pisa.
Lecture 36 OOP The STL Standard Template Library
Motivation for Generic Programming in C++
Generic Programming in C
Introduction to Generic Programming in C++
Programming with ANSI C ++
Standard Template Library
Lecture 7-2 : STL Iterators
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Templates in C++.
The C++ Algorithm Libraries
18 – Sequential Containers
Operator Overloading CSCE 121 J. Michael Moore
Lecture 7-2 : STL Iterators
Associative Structures
C++ Functions, Classes, and Templates
Introduction to the Standard Template Library
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
CMSC 202 Lesson 22 Templates I.
Elements are always copied when they are put into a container
Lists - I The List ADT.
Lists - I The List ADT.
Lecture 8-2 : STL Iterators and Algorithms
Parasol Lab, Texas A&M University
Templates I CMSC 202.
Lab4 problems More about templates Some STL
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Operator Overloading CSCE 121 Based on Slides created by Carlos Soto.
Standard Template Library
Presentation transcript:

Washington WASHINGTON UNIVERSITY IN ST LOUIS More on the STL: Function Objects and Generic Algorithms in the STL Fred Kuhns Computer Science and Engineering Applied Research laboratory Washington University in St. Louis

2 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Leverages Templates This is a simple, straight forward template function But it is limited since it only supports the comparison operator ‘ < ‘ defined for T A better solution is to allow the comparison function to be passed as an argument. // find minimum element in container supporting // the operetor[]() and types T supporting operators // operator<() and operator=()‏ template const T& min(const T* p, int sz)‏ { T* minval = &p[0]; for (int i = 1; i < sz; ++i)‏ if (p[i] < *minval) minval = &p[i]; return *minval; }

3 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Adding some flexibility Increased flexibility by permitting a wider variety of comparison operations But, now we have a function pointer adding overhead. // find minimum element in container supporting // the operetor[]() and types T supporting operator<(). template const T& min(const T*p, int sz, LT lt)‏ { T *minval = &p[0]; for (int i = 1; i < sz; ++i)‏ if (lt(p[i], *minval)) minval = &p[i]; return *minval; }

4 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Function Objects Now the comparison may be inlined and the function object may hold state template class MyComp { … bool operator()(X& a, X& b) {…} … } // find minimum element in container supporting // the operetor[]() and types T supporting operator<(). template const T& min(const T*p, int sz, LT lt)‏ { T* minval = &p[0]; for (int i = 1; i < sz; ++i)‏ if (lt(p[i], *minval)) minval = &p[i]; return *minval; }

5 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Another Example // assumes arithmetic types which permit 0 assignment // and operator+=()‏ template Sum { T sum_; public: Sum(T i=0) : sum_(i) {} void operator()(T x) {sum_ += x;} T result() const {return sum_;} }; void fn(list & ld)‏ { Sum sumObj; s = for_each(ld.begin(), ld.end(), sumObj); cout << “Sum = ” << sumObj.result() << endl; }

6 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Where do you find functors? Predefined set of arithmetic, relational and logical functors in the STL Function Object bases, Predicates, Arithmetic 1.Predefined set of function adaptors: Binders, Adapters and Negators Define your own

7 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Predefined Function Objects Each is a class template parameterized on the type of operands. See Primary use is as arguments to the generic functions #include plus intAdd; int i = 10, j = 20; int sum = intAdd(i, j); // sort() by default invokes the less-than operator vector names; … sort(names.begin(), names.end(), greater ()); creates tmp object (unnamed) ‏

8 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Predefined Function Objects defined bases provide standard names for types predicates: function that returns a bool // predefined base classes for operators template struct unary_function { typedef Arg argument_type; typedef Res result_type; }; template struct binary_function { typedef Arg first_argument_type; typedef Arg2 second_argument_type; typedef Res result_type; }; // example, STL less functor template struct less : public binary_function { bool operator()(const T&x, const T&y) const {return x < y;} };

9 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Predicates Compare element by element, in this case the elements of vi are compared to those of li. Finds the first element of vi that is NOT less than the corresponding element of li. What if I used less rather than less () in the call to missmatch() ? // example predicate template struct less : public binary_function { bool operator()(const T&x, const T&y) const {return x < y;} }; void fn(vector &vi, list & li)‏ { typedef list ::iterator LI; typedef vector ::iterator VI; pair pl; // find first pair of elements that do not match pl = mismatch(vi.begin(), vi.end(), li.begin(), less ()); … }

10 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Define your own predicate here we defined a predicate that returns true if a student is found with the same last name class Student { string lname, fname, mname; int idnum; … }; class Student_eq : public unary_function <Student, bool) { string name; public: explicit Student_eq(const string& n) : name(n) {} bool operator()(const Student&s) const {return s.lname == name;} }; void fn(list & sl)‏ { typedef list ::iterator SLI; SLI p = find_if(sl.begin(), sl,end(), Student_eq(“Smith”)); … }

11 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Adapters Binder: allows two parameter function objects to be used with one –bind the first or second argument to object’s data member. The remaining argument is taken from the call list. –I give examples in the following slides Adapter: member function and function pointer adapters –permits member function of an object to be called when using the generic algorithms Negater: negate result of predicate

12 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Binders Example where we explicitly create an object to hold the desired comparison value. Occurs often enough the a generalized mechanism is provided in the STL template lt : public unary_function { T arg2; public: explicit lt(const T& x) : arg2(x) {} bool operator()(const T& x) const {return x < arg2;} }; void fn(list &c)‏ { list ::const_iterator p = find_if(c.begin(),c.end(), lt (7) ); … }

13 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Binders template class binder2nd : public unary_function { protected: BinOp op; typename BinOp::second_argument_type arg2; public: binder2nd(const BinOp& x, const typename BinOp::second_argument_type&v)‏ : op(x), arg2(v) {} result_type operator()(const first_argument_type& x) const {return op(x, arg2);} }; template binder2nd bind2nd(const BinOp&op, const T&v)‏ { return binder2nd (op, v); } // example use void fn(list &c)‏ { list ::const_iterator p = find_if(c.begin(),c.end(),bind2nd(less, 7)); … } return type parameterized for operand and operator types

14 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Simpler version template struct less_than : public binder2nd, T> { explicit less_than(const T& x) : binder2nd(less (), x) {} }; void fn(list & c)‏ { list ::const_iterator p = find_if(c.begin(), c.end(), less_than (7)); }

15 Fred Kuhns (12/02/08) ‏ CS422 – Operating Systems Concepts Generic Algorithms generally, first two arguments are a pair of iterators marking the first and last elements Categories of algorithms –search –sorting/ordering –deletion/substitution –permutation –numeric –generation/mutation –relation –set –heap