Lecture 6 : Intro. to Generic Programming Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
PRESENTED BY MATTHEW GRAF AND LEE MIROWITZ Linked Lists.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Beginning C++ Through Game Programming, Second Edition
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Chapter 14: Overloading and Templates
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Data Structures Topic #3. Today’s Agenda Ordered List ADTs –What are they –Discuss two different interpretations of an “ordered list” –Are manipulated.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
CS 11 C++ track: lecture 8 Today: Inheritance. Inheritance (1) In C++ we create classes and instantiate objects An object of class Fruit "is-a" Fruit.
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.
Intro to Generic Programming Templates and Vectors.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
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
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
CS 11 C++ track: lecture 7 Today: Templates!. Templates: motivation (1) Lots of code is generic over some type Container data types: List of integers,
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.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Games Development 2 Overview & Entity IDs and Communication CO3301 Week 1.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
CSC Data Structures, Fall, 2008 Monday, September 29, end of week 5, Generic Functions and Classes in C++
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
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”
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CSE 1201 Object Oriented Programming ArrayList 1.
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.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Python Programing: An Introduction to Computer Science
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
Motivation for Generic Programming in C++
Module 20/21/22: The Standard Template Library
Phil Tayco Slide version 1.0 Created Sep 18, 2017
C++ Templates.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Dr. Bernard Chen Ph.D. University of Central Arkansas
Passing Arguments to a Function
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Linked Lists.
Private.
Introduction to Computer Science
Presentation transcript:

Lecture 6 : Intro. to Generic Programming Acknowledgement : courtesy of Prof. Dekai Wu lecture slides

Example : class Person class Person { public: void set_name(const string& n); void set_address(const string& adr); void set_ _address(const string& adr); string get_ _address() const; string get_name() const; string get_address() const; private: string name; string address; string _address; };

Example: class Person_Container as an array class Person_Container { public: Person_Container(int n) : MAX_SIZE(n), Size(0) { array = new Person [MAX_SIZE]; } int size() const { return Size; } void add_person(constPerson& pers); Person get_person(int i) const; Person delete_person(int i); private: const int MAX_SIZE; Person* array;// One-time pre-allocatedstorage int Size;// Number of Persons actually stored };

Container Class Classes that maintain collections of objects Templates work especially well for containers, since the logic to manage a container is often largely independent of the contents The operations on Person_Container can be: member functions of the Person_Container class. global functions that take a Person_Container & argument. Here we make global functions that print mailing labels for all the persons, and send s to invite them to our party.

Example: Operations on Person_Container void print_mailing_labels(const Person_Container& pc) { for (int i = 0; i < pc.size(); ++i) { Person pers = pc.get_person(i); cout<< pers.get_name() << endl; cout<< pers.get_address() << endl; //... } void invite_to_party(const Person_Container& pc) { for (int i = 0; i < pc.size(); ++i) { Person p = pc.get_person(i); string command = “cat party.txt| mail”; command += p.get_name(); system( command.c_str() );// Send invitation s }

Similar Code Note the similarities in both functions: they both set up a loop to do something for all persons in the container. We can expect that if we add more functions that do something with all persons, that these functions show the same similarities. So we could reuse one of the existing functions by copying it, and changing the name and the body of for-loop of the copy. In fact, that is what we did when we made the second function. However, code reuse by copying is often a bad idea. Why?

Array or Linked List? In some applications, it is very convenient that we implement Person_Container with an array; the get_person() member function takes only O(1) (constant) time, and we use that member function a lot. However, in other applications we may find that we frequently need to merge two Person_Container s into a single one, or split one Person_Container into two Person_Container s. Now the fact that we use an array is a drawback (why?); a linked list would have been more practical in this case. So let's implement a container class called Person_List representing a list of Person s.

Convert Int_List Code to Person_List Code We don't want to implement all the list functionality from scratch. Suppose that, fortunately, we find a Int_List in our archives: a class that implements a doubly linked list of integers. We “reuse by copying” again: we copy the Int_List, rename the copy to Person_List, and replace all occurrences of int to Person. Oops…we must be careful when we do the replacing; the size() member function of Person_List should still return an int …. Of course, we still want to be able to print mailing labels. However, the function that we have doesn't work for a Person_List. Changing the type of the argument is trivial. A more serious problem is that our Person_List class has no method to retrieve a Person by specifying its index. That is typical for many implementations of a list.

Convert Int_List _Code to Person_List _Code We could, of course, add a member function get_person(i) that retrieves a person by index, but what would that do to the running time of print_mailing_labels() ? Suppose that the original Int_List maintains a private pointer to the “current”element. get_current( ) => get the current element. set_first( ) => sets the pointer to the 1st item on the list. set_next( ) => sets the pointer to the next element. set_prev( ) => sets the pointer to the previous element. These functions return “-1”if there is nothing to point to. Since we applied “reuse by copying”, our Person_List class provides the same member functions as Int_List for manipulating the pointer to the “current”element in the list.

Example: print_mailing_labels() on Person_List void print_mailing_labels(const Person_List& pl) { if (pl.set_first() == -1) { return;// List is empty } do { Person p = pl.get_current(); cout<< p.get_name() << endl; cout<< p.get_address() << endl; } while (pl.set_next() != -1);// End of list is reached }

Example: invite_to_party() on Person_List void invite_to_party(const Person_List& pl) { if (pl.set_first() == -1) { return;// List is empty } do { Person p = pl.get_current(); string command = ''cat party.txt| mail ''; command += p.get_name(); system( command.c_str() );// Send invitation } while (pl.setnext() != -1);// End of list is reached }

3 Concepts of Container Classes In the previous examples, we can distinguish three concepts: the kind of container (list-based, array-based) the kind of objects stored in the container (Person, int) the kind of operations on the elements stored in the container (“do something for each element”). In our examples, there was a strong coupling between the three concepts: Whenever we change the type of the elements that we store, we have to re- implementthe container (by copying and changing). Next, we also have to change the functions that deal with this container.

Similar Code Again Suppose that we want to search if a certain element is present in a container. Conceptually, the algorithm for searching an element is independent of the type of element: compare the elements in the container with the search element, until you have found it, or no such element is present. However, in our examples, we would need separate functions for searching a Person with a specific name in a Person_Container searching a Person with a specific name in a Person_List searching a specific value in a Int_Container searching a specific value in a Int_List We would also need to implement a Int_Container first; for instance, by copying and changing the Person_Container

Generic Programming We see that strong coupling makes it impossible to reuse code without resorting to “code reuse by copying”. This leads to programs that are very inflexible, and difficult to maintain and extend. Isn't there a better way? It is possible to remove (or strongly reduce) the strong coupling between containers, contained elements, and operations on the elements of the container by applying generic programming(GP). One (narrow) view of GP is that it means “programming with types as parameters”. C++ supports GP through the template mechanism.

Example: max() reuse by copying int max(int a, int b) { if (a > b) { return a; } else { return b; } string max(const string& a, const string& b) { if (a > b) { return a; } else { return b; }

Example: max() reuse by copying Instead of copying, we write a single template definition : template T max(const T& a, const T& b) { if (a > b) { return a; } else { return b; }

Example: max() reuse by copying Now we can use max() for any type of arguments, as long as the arguments can be compared by '‘>'': template T max(const T& a, const T& b) { if (a > b) { return a; } else { return b; } main() { int x=4, y=8; string a(“hulk”), b(“jesse”); cout << max(x,y) << “is the larger number” << endl; cout << max(a,b) << “is the stronger wrestler” << endl; }

The Standard Template Library Containers are very common in programming, and several algorithms on container (searching for a specific element, searching for an element that satisfies some condition, sorting) occur in almost every non-trivial program. A lot of these general purpose containers can be found in the Standard Template Library, or STL for short. ANSI was so impressed by STL when it was first developed that it incorporated STL into the C++ Standard Library. Officially, STL is no longer a separate entity (except for a slightly extended versionfrom the original authors), but we still informally say “STL” to refer to that part of the C++ Standard Library.