CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.

Slides:



Advertisements
Similar presentations
Inserting a Node into a Specified Position of a Linked List To create a node for the new item newNode = new Node(item); To insert a node between two nodes.
Advertisements

Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
CSE Lecture 12 – Linked Lists …
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
C++ Templates Gordon College CPS212. Overview Templates Definition: a pattern for creating classes or functions as instances of the template at compile.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
CSE 250: Data Structures Week 3 January 28 – February 1, 2008.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Helpful C++ Transitions
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.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Linked Lists list elements are stored, in memory, in an arbitrary order explicit information (called a link) is used to go from one element to the next.
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Hashing CS 202 – Fundamental Structures of Computer Science II Bilkent.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
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.
ليست هاي پيوندي Linked Lists ساختمان داده ها و الگوريتم ها.
CMSC 202 Lesson 14 Copy and Assignment. Warmup Write the constructor for the following class: class CellPhone { public: CellPhone(int number, const string&
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
1 Working with Pointers An exercise in destroying your computer.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Data Structures Using C++1 Chapter 7 Stacks. Data Structures Using C++2 Chapter Objectives Learn about stacks Examine various stack operations Learn how.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
February 28, 2005 Introduction to Classes. Object Oriented Programming An object is a software bundle of related variables and methods. Software objects.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
1 CS 132 Spring 2008 Chapter 5 Linked Lists p
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
CMSC 202 Lesson 26 Miscellaneous Topics. Warmup Decide which of the following are legal statements: int a = 7; const int b = 6; int * const p1 = & a;
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Linked Data Structures
Pointer to an Object Can define a pointer to an object:
CS505 Data Structures and Algorithms
C++ Templates.
OOP-4-Templates, ListType
Lesson 14 Copy and Assignment
Stack and Queue APURBO DATTA.
LinkedList Class.
Templates II CMSC 202.
CMSC 341 Lecture 6 – Templates
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
CMSC 202 Lesson 22 Templates I.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Lesson 26 Miscellaneous Topics
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Stacks and Queues.
Templates I CMSC 202.
Data Structures & Algorithms
Lab4 problems More about templates Some STL
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Lesson 25 Miscellaneous Topics
Lists CMSC 202, Version 4/02.
Lists CMSC 202, Version 4/02.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
5.3 Implementing a Stack Chapter 5 – The Stack.
Presentation transcript:

CMSC 202 Lesson 23 Templates II

Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________ } template T& T temp = a; a = b; b = temp;

Class Templates Fundamental Idea  Define classes that operate on various types of objects  Shouldn’t matter what kind of object it stores Generic “collections” of objects Examples  Linked List  Queue  Stack  Vector  Binary Tree (341)  Hash Table (341)

Templated Classes Three key steps:  Add template line Before class declaration  Add template line Before each method in implementation  Change class-name to include template Add after the class-name wherever it appears Example  Let’s look at a Stack Collection of Nodes Each node has a templated piece of data and a pointer to next node Operations: push, pop

Non-templated Headers class Node { public: Node( const int& data ); const int& GetData(); void SetData( const int& data ); Node* GetNext(); void SetNext( Node* next ); private: int m_data; Node* m_next; }; class Stack { public: Stack(); void Push( const int& item ); int Pop(); private: Node* m_head; };

Templated Node template class Node { public: Node( const T& data ); const T& GetData(); void SetData( const T& data ); Node * GetNext(); void SetNext( Node * next ); private: T m_data; Node * m_next; }; template Node ::Node( const T& data ) { m_data = data; m_next = NULL; } template const T& Node ::GetData() { return m_data; } template void Node ::SetData( const T& data ) { m_data = data; } template Node * Node ::GetNext() { return m_next; } template void Node ::SetNext( Node * next ) { m_next = next; }

Templated Stack template class Stack { public: Stack(); void Push(const T& item); T Pop(); private: Node * m_head; }; template Stack ::Stack() { m_head = NULL; } template void Stack ::Push(const T& item) { Node * newNode = new Node (item); newNode->SetNext(m_head); m_head = newNode; } template T Stack ::Pop() { T data = m_head->GetData(); Node * temp = m_head; m_head = temp->GetNext(); delete temp; return data; }

Using the Templated Stack int main() { Stack stack; stack.Push(7); stack.Push(8); stack.Push(10); stack.Push(11); cout << stack.Pop() << endl; return 0; }

Multiple Templated Types template class Pair { public: Pair( ); ~Pair( ); Pair( const Pair & pair); bool operator== (const Pair & rhs) const; private: Key m_key; Data m_data; }; // Pair's equality operator template bool Pair ::operator== (const Pair & rhs) const { return m_key == rhs.m_key && m_data == rhs.m_data; }

Using the Pair Template int main ( ) { string bob = "bob"; string mary = "mary"; // use pair to associate a string and its length Pair boy (bob.length(), bob); Pair girl (mary.length(), mary); // check for equality if (boy == girl) cout << "They match\n"; return 0; }

Using the Pair Template (More) int main ( ) { // use Pair for names and Employee object Employee john, mark; Pair boss ("john", john); Pair worker( "mark", mark); if (boss == worker) cout << "A real small company\n"; return 0; }

Templates with Non-types? template class SmartArray { public: SmartArray ( ); // other members private: int m_size; T m_data[ size ]; }; template SmartArray ::SmartArray( ) { m_size = size; } Why does this work?

Templates as Parameters template void Sort ( SmartArray & theArray ) { // code here }

Templates with Friends template class SmartArray { friend ostream& operator (ostream& out, const SmartArray & theArray); // the rest of the SmartArray class definition }; template ostream& operator & theArray) { // code here } Use <> after the function name to indicate that this friend is a template!

Templates, Friends, and g++ G++ compiler is tricky  Must “forward declare” our templated class (essentially prototyping the class)  Must “forward declare” our overloaded friend (essentially prototyping the operator) // forward-declaring class template class FooClass; // forward-declaring insertion stream template ostream& operator<< (ostream& out, const FooClass &foo); template class FooClass { public: friend ostream& operator (ostream& out, const FooClass &foo); private: }; template ostream& operator<< (ostream& out, const FooClass &foo) { // implementation }

Compiling Templates Tricky…. Start with the normal stuff  Class declaration in.h file  Implementation in.cpp file Now’s the weird stuff… (ONLY for templates)  Remember, templated code is NOT really code, yet… the compiler must build the code  #include the.cpp at the end of the.h  Guard the.h AND the.cpp Why?  Because the.cpp #includes the.h, but the.h #includes the.cpp!!!  THEN you can use the -c switch for g++ to compile the.cpp  Everything else can just #include the.h file

Templated Node #ifndef NODE_H #define NODE_H template class Node { public: Node( const T& data ); const T& GetData(); void SetData( const T& data ); Node * GetNext(); void SetNext( Node * next ); private: T m_data; Node * m_next; }; #include "Node.cpp" #endif #ifndef NODE_CPP #define NODE_CPP #include "Node.h" template Node ::Node( const T& data ) { m_data = data; m_next = NULL; } template const T& Node ::GetData() { return m_data; } template void Node ::SetData( const T& data ) { m_data = data; } template Node * Node ::GetNext() { return m_next; } template void Node ::SetNext( Node * next ) { m_next = next; } #endif

Practice Let’s return to our Zoo classes…  Create a templated class called Cage It can hold a single animal  Constructor: does nothing  Enter(object) Puts an object in the cage, if another object was already in the cage, throw an exception (just a simple string message)  Leave() Removes an object from the cage, return the object

Challenge Create a Bag class  Templated  Insert a new item  Remove a random item No order to removal!  Hint: look up the rand() function and srand()