Templates, Iterators and STL

Slides:



Advertisements
Similar presentations
Chapter 5 introduces the often- used data structure of linked lists. This presentation shows how to implement the most common operations on linked lists.
Advertisements

CSC211 Data Structures Lecture 9 Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Chapter 12 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach to the.
Container Classes A container class is a data type that is capable of holding a collection of items. In C++, container classes can be implemented as.
 One of the tree applications in Chapter 10 is binary search trees.  In Chapter 10, binary search trees are used to implement bags and sets.  This presentation.
CSC212 Data Structure Lecture 14 Binary Search Trees Instructor: Prof. George Wolberg Department of Computer Science City College of New York.
 Chapter 2 introduces Object Oriented Programming.  OOP is a relatively new approach to programming which supports the creation of new data types and.
CSC212 Data Structure - Section AB Lecture 20 Hashing Instructor: Edgardo Molina Department of Computer Science City College of New York.
CSC212 Data Structure - Section FG Lecture 21 Quadratic Sorting Instructor: Zhigang Zhu Department of Computer Science City College of New York.
Exam Review 2 Chapter 5 – 9 CSC212 RS March 31, 2011, CS Dept, CCNY.
 Chapter 10 introduces trees.  This presentation illustrates the simplest kind of trees: Complete Binary Trees. Complete Binary Trees Data Structures.
CSC212 Data Structure - Section FG Lecture 9 Linked Lists Instructor: Zhigang Zhu Department of Computer Science City College of New York.
Exam Review 2 Chapter 5 – 9 CS211 November 05,2007, CS Dept, MHC.
 An important topic: preconditions and postconditions.  They are a method of specifying what a function accomplishes. Preconditions and Postconditions.
L l Chapter 4 introduces the often- used linked list data structures l l This presentation shows how to implement the most common operations on linked.
 Chapter 9 introduces the technique of recursive programming.  As you have seen, recursive programming involves spotting smaller occurrences of a problem.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
CSC212 Data Structure - Section FG Lecture 12 Stacks and Queues Instructor: Zhigang Zhu Department of Computer Science City College of New York.
 Chapter 8 introduces the queue data type.  Several example applications of queues are given in that chapter.  This presentation describes the queue.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
P An important topic: preconditions and postconditions. p They are a method of specifying what a function accomplishes. Preconditions and Postconditions.
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
P An important topic: preconditions and postconditions. p They are a method of specifying what a function accomplishes. Illinois State University Department.
CSC211 Data Structures Lecture 20 Hashing Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
 An important topic: preconditions and postconditions.  They are a method of specifying what a method accomplishes. Preconditions and Postconditions.
This lecture introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how.
CSC211 Data Structures Lecture 21 Quadratic Sorting Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
CSC211 Data Structures Lecture 18 Heaps and Priority Queues Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
CSC212 Data Structure - Section FG Lecture 11 Templates, Iterators and STL Instructor: Professor Zhigang Zhu Department of Computer Science City College.
P p Chapter 10 introduces trees. p p This presentation illustrates the simplest kind of trees: Complete Binary Trees. Complete Binary Trees Data Structures.
Container Classes  A container class is a data type that is capable of holding a collection of items.  In C++, container classes can be implemented as.
CSC212 Data Structure - Section AB Lecture 13 Recursive Thinking Instructor: Edgardo Molina Department of Computer Science City College of New York.
CSC212 Data Structure Lecture 16 Heaps and Priority Queues Instructor: George Wolberg Department of Computer Science City College of New York.
1 CSC212 Data Structure Lecture 4 Container Classes Instructor: George Wolberg Department of Computer Science City College of New York.
Xiaoyan Li CSC211 Data Structures Lecture 2 ADT and C++ Classes (I) Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 2 ADT and C++ Classes (I) Instructor: Zhigang Zhu Department of Computer Science City.
Exam Review 2 Chapter 5 – 9 CSC212 FG CS Dept, CCNY.
Templates 1. Template Functions 2. Template Class 3. Bag Class Template 4. Standard Library Template (STL) Classes Standard Library Template (STL) Classes.
 Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes.  This presentation shows how.
CSC212 Data Structure - Section BC
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
C++ Templates.
Collection Classes A Collection class is a data type that is capable of holding a group of items. In Java, Collection classes can be implemented as a class,
The Bag and Sequence Classes with Linked Lists
Using a Stack Chapter 6 introduces the stack data type.
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Chapter 5 – 9 CSC212 AB April 03, CS Dept, CCNY
Chapter 5 – 9 CSC212 KL Nov 8, CS Dept, CCNY
Using a Stack Chapter 6 introduces the stack data type.
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
CSC212 Data Structure - Section AB
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Chapter 5 – 9 CSC212 RS April 08, CS Dept, CCNY
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
Using a Stack Chapter 6 introduces the stack data type.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Using a Stack Chapter 6 introduces the stack data type.
Hash Tables Chapter 12 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Really reusable software
Using a Queue Chapter 8 introduces the queue data type.
Linked Lists in Action Chapter 5 introduces the often- used data structure of linked lists. This presentation shows how to implement the most common.
Using a Queue Chapter 8 introduces the queue data type.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Presentation transcript:

Templates, Iterators and STL CSC212 Data Structure Lecture 9 Templates, Iterators and STL Instructor: George Wolberg Department of Computer Science City College of New York

Topics Template Functions and Template Classes Iterators for code that is meant be reused in a variety of settings in a single program Iterators step through all items of a container in a standard manner Standard Template Library (STL) the ANSI/ISO C++ Standard provides a variety of container classes in the STL

Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation shows how to implement and use the simplest kinds of templates: template functions. Templates are an important part of C++ that allows a programmer to reuse existing code for new purposes. In some sense, templates ensure that you don’t have to continually “reinvent the wheel.” This lecture introduces how to implement and use template functions. The best time for the lecture is just before the students read Chapter 6. CHAPTER 6 Data Structures and Other Objects

Finding the Maximum of Two Integers Here’s a small function that you might write to find the maximum of two integers. int maximum(int a, int b) { if (a > b) return a; else return b; } To illustrate template functions, let’s look at this simple function. It would appear as part of a program that needs to find the larger of two integers. The function returns a copy of the larger of its two arguments.

Finding the Maximum of Two Doubles Here’s a small function that you might write to find the maximum of two double numbers. double maximum(double a, double b) { if (a > b) return a; else return b; } Suppose your program also needs to find the larger of two double numbers. Then you could add a second function for double numbers. By the way, you may use the same name, maximum, for the two functions. The compiler is smart enough to determine which function your program is using at any given point, by looking at the types of the parameters.

Finding the Maximum of Two Gongfus Here’s a small function that you might write to find the maximum of two Gongfus. Gong Fu (Kung Fu) Martial Arts Gongfu maximum(Gongfu a, Gongfu b) { if (a > b) return a; else return b; } Shaolin martial arts (kung fu) and philosophy Suppose your program also has another data type, called Gongfu . This could be a class that you wrote yourself for some purpose. Anyway, perhaps Gongfu objects can be compared with the > operation (because the Gongfu implementation includes an overloaded > operator). In this case, your program might have a third function to compare two Gongfu objects.

Finding the Maximum of Two ... Here’s a small function that you might write to find the maximum of two ...using typedef typedef ..int.... data_type data_type maximum(data_type a, data_type b) { if (a > b) return a; else return b; } But you need to re-compile your program every time you change the data_type, and you still only have one kind of data type Of course, you know how to use typedef to define data-type as difference types and use them for different purposes. However there are two problems in this approach: Everytime you change the data_type, you need to re-compile your program. The only convienence is that you don’t need to change your data type (e.g. int) all across your big program – you only need to change the type keyword right after the typedef keyword You still only have one data_type... you cannot use this function to compare two integers as well as two doubles at the same time. So need to write one version for each data type anyway

One Hundred Million Functions... Suppose your program uses 100,000,000 different data types, and you need a maximum function for each... int maximum(Hoo a, Hoo b) { if (a > b) return a; else return b; } int maximum(Doo a, Doo b) { if (a > b) return a; else return b; } int maximum(Hoo a, Hoo b) { if (a > b) return a; else return b; } int maximum(Moo a, Moo b) { if (a > b) return a; else return b; } int maximum(Hoo a, Hoo b) { if (a > b) return a; else return b; } int maximum(Noo a, Noo b) { if (a > b) return a; else return b; } int maximum(Doo a, Doo b) { if (a > b) return a; else return b; } int maximum(Doo a, Doo b) { if (a > b) return a; else return b; } int maximum(Noo a, Noo b) { if (a > b) return a; else return b; } int maximum(Moo a, Moo b) { if (a > b) return a; else return b; } int maximum(Noo a, Noo b) { if (a > b) return a; else return b; } int maximum(Moo a, Moo b) { if (a > b) return a; else return b; } int maximum(Foo a, Foo b) { if (a > b) return a; else return b; } int maximum(Foo a, Foo b) { if (a > b) return a; else return b; } int maximum(Foo a, Foo b) { if (a > b) return a; else return b; } int maximum(Poo a, Poo b) { if (a > b) return a; else return b; } int maximum(Poo a, Poo b) { if (a > b) return a; else return b; } int maximum(Boo a, Boo b) { if (a > b) return a; else return b; } int maximum(Poo a, Poo b) { if (a > b) return a; else return b; } int maximum(Koo a, Koo b) { if (a > b) return a; else return b; } int maximum(Boo a, Boo b) { if (a > b) return a; else return b; } In fact, for your next programming assignment, I’m going to give you a printed list of 100,000,000 different data types, each of which has the > operator defined. Your job will be to implement a maximum function for each of the types. How long do you think this job will take? How many of you think it will take more than one day’s work? Raise your hands. Okay, now how many of you think you’ll need less than a day--in fact less than five minutes? Raise your hands. These are the people that have been reading ahead in Chapter 6 about a feature called template functions. int maximum(Boo a, Boo b) { if (a > b) return a; else return b; } int maximum(Joo a, Joo b) { if (a > b) return a; else return b; } int maximum(Koo a, Koo b) { if (a > b) return a; else return b; } int maximum(Koo a, Koo b) { if (a > b) return a; else return b; } int maximum(Ioo a, Ioo b) { if (a > b) return a; else return b; } int maximum(Joo a, Joo b) { if (a > b) return a; else return b; } int maximum(Knafn a, Knafn b) { if (a > b) return a; else return b; } int maximum(Joo a, Joo b) { if (a > b) return a; else return b; } int maximum(Knafn a, Knafn b) { if (a > b) return a; else return b; } int maximum(Ioo a, Ioo b) { if (a > b) return a; else return b; } int maximum(Knafn a, Knafn b) { if (a > b) return a; else return b; } int maximum(Ioo a, Ioo b) { if (a > b) return a; else return b; } int maximum(Coo a, Coo b) { if (a > b) return a; else return b; } int maximum(Coo a, Coo b) { if (a > b) return a; else return b; } int maximum(Coo a, Coo b) { if (a > b) return a; else return b; } int maximum(Loo a, Loo b) { if (a > b) return a; else return b; } int maximum(Goo a, Goo b) { if (a > b) return a; else return b; } int maximum(Loo a, Loo b) { if (a > b) return a; else return b; } int maximum(Goo a, Goo b) { if (a > b) return a; else return b; } int maximum(Loo a, Loo b) { if (a > b) return a; else return b; } int maximum(Goo a, Goo b) { if (a > b) return a; else return b; }

A Template Function for Maximum This template function can be used with many data types. template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Item: Underlying data type, template parameter With two features... This is our first example of a template function. It is a single function that depends on an underlying data type that I’ve called Item. The actual Item type could be any of many different types: int, double, char--in fact any type that has two features: (1) the data values can be compared with the > operator, and (2) the data type has a copy constructor. (By the way, where is the copy constructor needed? It is needed to initialized the two parameters from their actual arguments, and also needed when the function returns a value.) Anyway, let’s look at the pattern for converting an ordinary function to a template function...

A Template Function for Maximum When you write a template function, you choose a data type for the function to depend upon... template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Our maximum function depends on the type of the item that we are comparing. This is the type of the two parameters, and also the return type. So, in the template function, we choose a name for this type--we use the name Item--and you use that name instead of the actual data type name.

A Template Function for Maximum A template prefix is also needed immediately before the function’s implementation: template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Before an implementation, a special template prefix is also require. The prefix consists of the keyword template followed by angle brackets. Inside the angle brackets is the keyword class and the name that you choose to describe the underlying data type.

Using a Template Function Once a template function is defined, it may be used with any adequate data type in your program... template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } cout << maximum(1,2); cout << maximum(1.3, 0.9); ... Here are two examples of how the single template function can be used in two different ways in a single program. In the first example, the compiler sees two integer arguments, so the compiler will automatically create a version of the function where the Item is an int. In the second example, the compiler sees two double arguments, so the compiler will automatically create a version of the function where the Item is a double. We could have a third example where the two arguments were Gongfu objects, and the compiler would automatically create a version of the function where the Item is a Gongfu. What’s behind the scene?

Finding the Maximum Item in an Array Here’s another function that can be made more general by changing it to a template function: int array_max(int data[ ], size_t n) { size_t i; int answer; assert(n > 0); answer = data[0]; for (i = 1; i < n; i++) if (data[i] > answer) answer = data[i]; return answer; } Here’s another function that can be improved by making it into a template function. In this form, the function can find the largest integer in an array of integers. But it can’t be used for an array of double numbers, or an array of some other kind of objects. In this case, the function depends on the underlying data type of the components of the array. We can call this component type Item, and rewrite the function as a template function...

Finding the Maximum Item in an Array Here’s the template function: template <class Item> Item array_max(Item data[ ], size_t n) { size_t i; Item answer; assert(n > 0); answer = data[0]; for (i = 1; i < n; i++) if (data[i] > answer) answer = data[i]; return answer; } Here’s the template version. Notice these things: 1. the template prefix 2. The change of the data type of at least one parameter (the array) 3. The change of the return type (this might not occur for every template function) 4. In the implementation, we can use the Item type for local variables

Template Functions: a summary A template function depends on an underlying data type – the template parameter. More complex template functions and template classes are discussed in Chapter 6. Presentation copyright 1997, Addison Wesley Longman, For use with Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch. Some artwork in the presentation is used with permission from Presentation Task Force (copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyright Corel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image Club Graphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc). Students and instructors who use Data Structures and Other Objects Using C++ are welcome to use this presentation however they see fit, so long as this copyright notice remains intact. A quick summary . . .

Template Classes How to turn our node class into node template class template <class Item> precedes the node class definition value_type -> Item Outside the template class definition template prefix precedes each function prototype and implementation node -> node <Item> Exercise: Turn node into node template class handout node1 ....then node2 Exercise: Turn node into template node Tell them the basic changes Hand out two sheets for node1.h and node1.cpp : class definition and function prototype; implementation file (part) Hand out two sheets for node2.h and node2.cpp: check if you do it correctly – more changes?

Template Classes node template class How to turn our node class into node template class (continued) The implementation file name with .template extension (instead of .cpp) – cannot be compiled! it should be included in the header by #include “node2.template” eliminate any using directives in the implementation file, so you must write std::size_t, std::copy, etc. More changes ... please read Chapter 6 More changes? For bag 4 Outside of member functions and class definition size_type -> typename bag<Item>::size_type

Template Classes How to use it ? node<int>* ages = NULL; list_head_insert(ages,18); node<string> name; name.set_data(“Jorge”); node<point> *seat; seat = new node<point>; (*seat).set_data(point(2,4)); You need : point3-ppt.html (newpoint.h, newpoint.cpp) node2-ppt.html (node2.h, node2.template)

All you need to know about Templates Template Function a template prefix before the function implementation template <class Item1, class Item2, ...> Function Prototype a template prefix before the function prototypes Template Class a template prefix right before the class definition Instantiation template functions/classes are instantiated when used Better Understanding of classes and functions

Homework node<int>* ages = NULL; list_head_insert(ages,18); node<string> name; name.set_data(“Jorge”); node<point> *seat; seat = new node<point>; (*seat).set_data(point(2,4)); Write a small program n2demo.cpp with the lines in the previous slide, make sure you have the correct include and using directives. Then print out the data in node *ages, name and *seat. Try to run the program with point.h, point.cpp (online with lecture 3) node2.h, node2.template (online today) Note: you only need to compile point.cpp with your n2demo.cpp Turn in n2demo.cpp and the output in paper version on Wednesday

Iterators We are going to see how to build an iterator for the linked list so that each of the containers can build its own iterator(s) easily A node_iterator is an object of the node_iterator class, and can step through the nodes of the linked list

Reviews:Linked Lists Traverse How to access the next node by using link pointer of the current node the special for loop still works with template template <class Item> std:: size_t list_length(const node<Item>* head_ptr) { const node<Item> *cursor; std:: size_t count = 0; for (cursor = head_ptr; cursor != NULL; cursor = cursor->link()) count++; return count; }

Linked Lists Traverse using Iterators It would be nicer if we could use an iterator to step through a linked list following the [...) left-inclusive pattern template <class Item> std:: size_t list_length(const node<Item>* head_ptr) { const_node_iterator<Item> start(head_ptr), finish, position; std:: size_t count = 0; for (position = start; position != finish; ++position) count++; return count; }

node_iterator key points: node template class handout! derived from std::iterator (may NOT exist!) node_iterator<Item> position; a private variable - a pointer to current node node <Item>* current; * operator – get the current data using the notation *position Two versions of the ++ operator prefix version: ++position; postfix ver: position++ Comparison operators == and != Two versions of the node_iterator node_iterator and const_node_iterator

Linked List Version the bag Template Class with an Iterator Most of the implementation of this new bag is a straightforward translation of the bag in Chapter 5 that used an ordinary linked list Two new features Template class with a underlying type Item iterator and const_iterator – defined from node_iterator and const_node_iterator, but use the C++ standard [...) left inclusive pattern bag template class

The C++ standard [...) pattern You can use an iterator to do many things! bag<int> b; bag<int>::iterator position; // this iterator class is defined in the bag class std::size_t count =0; b.insert(18); ... for (position = b.begin(); position!= b.end(); ++position) // step through nodes { count++; cout << *position << endl; // print the data in the node }

Standard Template Library (STL) The ANSI/ISO C++ Standard provides a variety of container classes in the STL set, multiset, stack, queue, string, vector Featured templates and iterators For example, the multiset template class is similar to our bag template class More classes summarized in Appendix H

Summary Five bag implementations A template function depends on a underlying data type (e.g Item) which is instantiated when used. A single program may has several different instantiations of a template function A template class depends on a underlying data type A iterator allows a programmer to easily step through the items of a container class The C++ STL container classes are all provided with iterators