CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.

Slides:



Advertisements
Similar presentations
Lists: An internal look
Advertisements

Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
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,
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; }
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
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.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
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.
Templates and the STL.
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 )
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
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’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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,
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
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)‏
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
©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.
1 Iterators Good reference site:
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.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
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
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
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.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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)
Overview of STL Function Objects
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
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 (STL)
Chapter 15: Overloading and Templates
The C++ Algorithm Libraries
ADT Implementations: Templates and Standard Containers
Elements are always copied when they are put into a container
Abstraction: Generic Programming, pt. 2
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:

CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm (Austern pp. 13): template Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; } Which kinds of iterators will work with this algorithm? How can we determine that from the algorithm itself?

CSE 332: C++ Algorithms II Key Ideas: Concepts and Models A concept gives a set of type requirements –Classify/categorize types (e.g., random access iterators) –Tells whether or not a type can or cannot be used with a particular algorithm (get a compiler error if it cannot) E.g., in the examples from last time, we could not use a linked list iterator in find1 or even find2, but we can use one in find Any specific type that meets the requirements is a model of that concept –E.g., list ::iterator vs. char * in find Different abstractions (bi-linked list iterator vs. char array iterator) No inheritance-based relationship between them But both model iterator concept necessary for find

CSE 332: C++ Algorithms II Concepts and Models, Continued What very basic concept does the last statement of find, (the line return first; ) assume? –Asked another way, what must be able to happen to first when it’s returned from function find ? –Same requirement imposed by by-value iterator parameters What other capabilities are required of the Iterator and T type parameters by the STL find algorithm ? template Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; }

CSE 332: C++ Algorithms II Matching an Algorithm to the Iterators it Needs Category/ Operation OutputInputForwardBidirectional Random Access Read =*p (r-value) =*p (r-value) =*p (r-value) =*p (r-value) Access -> [] Write *p= (l-value) *p= (l-value) *p= (l-value) *p= (l-value) Iteration = -= Comparison == != == != = What STL iterator category does find require?

CSE 332: C++ Algorithms II Iterator Concept Hierarchy Input IteratorOutput Iterator Forward Iterator Bidirectional Iterator Random Access Iterator value persists after read/write values have locations can express distance between two iterators read or write a value (one-shot) Singly-inked-list style access ( forward_list ) Bi-linked-list style access ( list ) Array/buffer style access ( vector, deque ) “destructive” read at head of stream ( istream ) “transient” write to stream (ostream) is-a ( refines )

CSE 332: C++ Algorithms II What if an Algorithm Has Alternative Versions? Static dispatching –Implementations provide different signatures –Iterator type is evaluated at compile-time –Links to the best implementation Notice how type tags are used // Based on Austern, pp. 38, 39 template void move (Iter i, Distance d, fwd) { while (d>0) {--d; ++i;} // O(d) } template void move (Iter i, Distance d, rand) { i += d; // O(1) } template void move (Iter i, Distance d) { move (i, d, iterator_traits :: iterator_category() ) } concrete tag (empty struct) type default constructor (call syntax) concrete tag (empty struct) type

CSE 332: C++ Algorithms II Iterator Traits and Category Type Tags Need a few concrete types to use as tags –E.g., empty structs –E.g., input, output, fwd, bidir, and rand Tags provide yet another associated type for iterators –Iterator category –Again, made available by using the traits idiom struct input {}; // empty structs for type tags struct output {}; struct fwd : public input {}; // note inheritance struct bidir : public fwd {}; struct rand : public bidir {}; template struct iterator_traits {... typedef typename I::iterator_category iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; (actually, random_access_iterator_tag )

CSE 332: C++ Algorithms II Can Extend STL Algorithms with Callable Objects Make the algorithms 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 containe Each callable object does a single, specific operation –E.g., returns true if first value is less than second value Algorithms often have overloaded versions –E.g., sort that takes two iterators (uses operator< ) –E.g., sort that takes two iterators and a binary predicate, uses the binary predicate to compare elements in range

CSE 332: C++ Algorithms II Callable Objects and Adapters Callable objects support function call syntax –A function or function pointer bool (*PF) (const string &, const string &); // function pointer bool string_func (const string &, const string &); // function –A struct or class providing an overloaded operator() struct strings_ok { bool operator() (const string &s, const string &t) { return (s != “quit”) && (t != “quit”); } }; –A lambda expression (unnamed inline function) [quit_string] (const string &s, const string &t) -> bool {return (s != quit_string) && (t != quit_string);} Adapters further extend callable objects –E.g., bind any argument using bind and _1 _2 _3 etc. –E.g., wrap a member function using mem_fn –E.g., wrap callable object with function (associates types)

CSE 332: C++ Algorithms II Using Functions with 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; } pass function name heap object

CSE 332: C++ Algorithms II Using Function Objects with an Algorithm count_if algorithm –Generalizes the count algorithm –Instead of comparing for equality to a value –Applies a given predicate function object (functor) –If functor’s result is true, increases count #include using namespace std; template // covers many types struct odd { bool operator() (T t) const { return (t % 2) != 0; } }; int main (int, char * []) { vector v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(2); cout << "there are " << count_if(v.begin(), v.end(), odd ()) << " odd numbers in v" << endl; return 0; } /* output is there are 2 odd numbers in v */

CSE 332: C++ Algorithms II Concluding Remarks STL algorithms give you useful, generic functions –Combine easily with a variety of containers/iterators –Support many common data structure manipulations Finding and modifying values, re-ordering, numeric operations –Reusing them saves you from writing/debugging code Many STL algorithms can be extended –Especially by plugging callable objects (functors) into them –C++11 lambdas & the bind function give new ways to do that Think about how iterators and algorithms combine –Think about which category of iterator a container provides –Think about the concept each iterator models –Think about the type requirements an algorithm imposes –Think about which combinations are valid, accordingly