1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

Feichter_DPG-SYKL03_Bild-01. Feichter_DPG-SYKL03_Bild-02.
Final and Abstract Classes
Classes and Objects in Java
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 14 Inheritance. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Inheritance Basics Derived classes, with.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
1 Copyright © 2013 Elsevier Inc. All rights reserved. Appendix 01.
Chapter 3: Linked List Tutor: Angie Hui
Introduction to Computation and Problem
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Lecture 15 Linked Lists part 2
Solve Multi-step Equations
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Chapter 17 Linked Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Double linked list Lai Ah Fur. The structure of node class IntDLLNode { int info; IntDLLNode next = null, prev = null; IntDLLNode() { } IntDLLNode(int.
Linked Lists Chapter 4.
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Data Structures Using C++
Double-Linked Lists and Circular Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
ABC Technology Project
CSE Lecture 12 – Linked Lists …
EU market situation for eggs and poultry Management Committee 20 October 2011.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
© 2012 National Heart Foundation of Australia. Slide 2.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.
25 seconds left…...
Analyzing Genes and Genomes
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Pointers and Arrays Chapter 12
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Pointers and Linked Lists.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 14: More About Classes.
Energy Generation in Mitochondria and Chlorplasts
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
1 Abstract Data Types Chapter 1. 2 Objectives You will be able to: 1. Say what an abstract data type is. 2. Implement a simple abstract data type in C++
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
1 Linked Lists II Doubly Linked Lists Chapter 3. 2 Objectives You will be able to: Describe, implement, and use a Doubly Linked List of integers.
1 Introduction to Object Oriented Programming Chapter 10.
1 Linked Lists Chapter 3. 2 Objectives You will be able to: Describe an abstract data type for lists. Understand and use an implementation of a List ADT.
C++ Templates.
ADT Implementations: Templates and Standard Containers
Presentation transcript:

1 Linked Lists III Template Chapter 3

2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.

3 Issues in the int List Class The list can only hold integers. Solution: Make it a template.

4 Templates Templates are a feature in C++ that permit code to be more reusable. They have blanks, called parameters, that can be automatically filled in with type names at compile time. Rather than having to define separate classes for lists of ints, doubles, Circles, Dogs, Cats, etc., we can define a single List template. A user of the template can supply the name of the class that will be the data in list nodes. The compiler handles the substitution of the class name specified by the user for the parameter into the template definition. Result is a List class specialized for the users class.

5 Limitations of Template A class used as a template parameter must meet certain requirements. Must implement all operators used by the template methods. Typically = (Assignment operator) Copy constructor

6 Templates We have two kinds of templates in C++. Function templates. Class templates. In each, parameters can be specified for one or more types. The parameters are used as if they were real type names. The compiler substitutes real type names, specified by the user, for the parameters when the template is used.

7 C++ Templates The word template is a C++ keyword In front of a function definition, it specifies that what follows is … a pattern for a function definition not a real function definition. Type parameters appear within angle brackets ( ) before the function definition. Normal function parameters appear within parentheses, as in normal function definitions.

8 Caution A function template cannot be split across files. Specification and implementation must be in the same file. Just a.h file. No.cpp file.

9 A Function Template template T is a parameter void Swap (T &first, T &second) { T temp = first; first = second; second = temp; } The keyword typename can be used instead of the keyword class in the first line.

10 Function Template Instantiation When the compiler encounters a call to a function defined as a template, it generates a real function definition substituting the type(s) of the function arguments for the template parameter(s). The function call looks exactly like a call to a normally defined function. Example: swap (a[i], a[i+1]);

11 Class Templates We can define templates for classes as well as for functions. Specify one or more template parameters in front of the class definition. The class definition uses the parameters as if they were real class names. Real class names must be provided as values for the parameters whenever the template is used.

12 General Form Of Class Template Declaration template <class TypeParam1, class TypeParam2,..., class TypeParamN> class SomeClass { //... members of SomeClass... }; Within the class definition, the class parameters TypeParam1, TypeParam2, … TypeparamN can be used as if they were real class names. The parameter names can be any valid C++ name. (Same rules as for variable names.) When the class is used, real class names will be provided and substituted for the parameters. class is a C++ keyword here.

13 Alternative Form Keyword typename can be used instead of keyword class in the template parameter list. template <typename TypeParam1, typename TypeParam2,..., typename TypeParamN> class SomeClass { //... members of SomeClass... };

14 Instantiating Class Templates Instantiate the template by writing a declaration of form SomeClass objectName; where Type represents a real class name and SomeClass is the name of the template class. Passes Type as an argument to the class definition template. Examples: Stack intStack; Stack stringStack; Compiler will generate two distinct definitions of Stack Two instances of the class definition One for ints and one for strings.

15 Rules For Class Templates 1. Member functions outside the class declaration must be function templates. 2. Member functions must be defined in the same file as the class declaration. 3. All uses of the template class name as a type must be parameterized.

16 Convert intDLList into a List Template Create a new project. List_Template_Demo Copy the files from intDLList2 into the project directory _01_24_Doubly_Linked_List_2/ _01_24_Doubly_Linked_List_2/ Add the.h file to the project. Rename as DLList.h

17 Convert intDLList into a List Template Modify the existing code for intDLList to make it a template. Have to copy the function definitions from the.cpp file into the.h file. Replace int by a class parameter. Replace class names by new parameterized class names.

18 The Node Class Definition //************************ DLList.h ***************** // Doubly-linked list template #ifndef DLLIST_H #define DLLIST_H template class DLLNode { public: T info; DLLNode *next; DLLNode *prev; DLLNode(T el, DLLNode *ptr1 = 0, DLLNode *ptr2 = 0) { info = el; next = ptr1; prev = ptr2; } };

19 Problem with the Listhead In the intDLList we create the Listhead with an info value of 0. The value is never used. We can't do this with a template. For an arbitrary class, T, 0 might not be a valid value. We need a constructor for class DLLNode that doesn't specify a value for info. Leaves info uninitialized in the Listhead.

20 Default Constructor for DLLNode Add to DLLNode class defintion: DLLNode() { next = 0; prev = 0; }

21 DLList Class Definition template class DLList { private: DLLNode * ListHead; public: DLList() { ListHead = new DLLNode (); ListHead->next = ListHead; ListHead->prev = ListHead; }

22 DLList Class Definition DLList(const DLList & original); DLList& operator=(const DLList & original); ~DLList(); int isEmpty() const { return ListHead->next == ListHead; } void addToHead(const T&); void addToTail(const T&); T deleteFromHead(); // Delete the head and return its info; T deleteFromTail(); // Delete the tail and return its info; void deleteNode(const T&); bool isInList(const T&) const; void printAll() const; };

23 Destructor template DLList ::~DLList(void) { while (!isEmpty()) { DLLNode *p = ListHead->next->next; delete ListHead->next; ListHead->next = p; }

24 addToHead template void DLList ::addToHead(const T& el) { DLLNode *p = new DLLNode (el); p->next = ListHead->next; p->prev = ListHead; ListHead->next->prev = p; ListHead->next = p; }

25 addToTail template void DLList ::addToTail(const T& el) { DLLNode *p = new DLLNode (el); p->next = ListHead; p->prev = ListHead->prev; ListHead->prev->next = p; ListHead->prev = p; }

26 deleteFromHead template T DLList ::deleteFromHead() { if (isEmpty()) { throw("Attempt to delete from empty list"); } T el = ListHead->next->info; DLLNode *tmp = ListHead->next; ListHead->next->next->prev = ListHead; ListHead->next = ListHead->next->next; delete tmp; return el; }

27 deleteFromTail template T DLList ::deleteFromTail() { if (isEmpty()) { throw("Attempt to delete from empty list"); } T el = ListHead->prev->info; DLLNode *tmp = ListHead->prev; ListHead->prev->prev->next = ListHead; ListHead->prev = ListHead->prev->prev; delete tmp; return el; }

28 deleteNode template void DLList ::deleteNode(const T& el) { DLLNode *p = ListHead->next; while (p != ListHead && p->info != el) { p = p->next; } if (p == ListHead) { return; // It's not there. Claim success! } // p points to node to be deleted. p->prev->next = p->next; p->next->prev = p->prev; delete p; }

29 isInList template bool DLList ::isInList(const T& el) const { DLLNode *p = ListHead->next; while (p != ListHead && p->info != el) { p = p->next; } return p != ListHead; }

30 printAll template void DLList ::printAll() const { if (isEmpty()) { cout << "List is empty\n"; return; } DLLNode *p = ListHead->next; while (p != ListHead) { cout info << endl; p = p->next; } cout << endl; }

31 Copy Constructor // Copy constructor template DLList ::DLList(const DLList & original) { ListHead = new DLLNode (); ListHead->next = ListHead; ListHead->prev = ListHead; // Copy the original list DLLNode* p = original.ListHead->next; while (p != original.ListHead) { addToTail(p->info); p = p->next; }

32 Assignment Operator // Assignment operator template DLList & DLList ::operator=(const DLList & original) { if (this == &original) // Check for self assignment { return *this; } while (!isEmpty()) // Delete the current list contents { deleteFromTail(); } delete ListHead;

33 Assignment Operator ListHead = new DLLNode (); ListHead->next = ListHead; ListHead->prev = ListHead; // Copy the original list DLLNode * p = original.ListHead->next; while (p != original.ListHead) { addToTail(p->info); p = p->next; } return *this; }

34 Testing the Template Adapt the test driver for intDLList to use the DLList template. Parmeterize the template for int. Results should be identical to previous.

35 main.cpp #include #include "DLList.h" using namespace std; int main() { DLList myList;... myList = new DLList ();... myList = new DLList ();... Everything else is unchanged.

36 Program Running