06b_template

06b_template - Data Structures - CSCI 102 CS102 C+...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Data Structures - CSCI 102 Copyright © William C. Cheng CS102 C++ Templates Bill Cheng http://merlot.usc.edu/cs102-s11
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Stacks/Queues (Ch 18) Topics to cover 2 Data Structures - CSCI 102 Copyright © William C. Cheng C++ Abstract Data Types Vectors (Ch 22) Linked Lists (Ch 17) Templates (Ch 14)
Background image of page 2
The Linked List and Vector classes we made are useful, but what if we want a List to store something besides int types? 3 Data Structures - CSCI 102 Copyright © William C. Cheng Flexible Linked Lists Do we have to define a whole new List class for each data type? What about that syntax we use on vectors? vector< int > numbers; That seems (and is) absurd
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
C++ provides a feature called a template to help prevent duplicate code 4 Data Structures - CSCI 102 Copyright © William C. Cheng Templates A template is a generic pattern for creating methods and classes Consider the following function: int add( int x, int y) { return x + y; }
Background image of page 4
We have a function to add two integers: 5 Data Structures - CSCI 102 Copyright © William C. Cheng Templates What about combining two strings? string add(string x, string y) { return x + y; } int add( int x, int y) { return x + y; } What if we need other functions to add things like two double types or two Point types?
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
The only differences between these two functions are highlighted in red below: 6 Data Structures - CSCI 102 Copyright © William C. Cheng Templates string add( string x, string y) { return x + y; } int add( int x, int y) { return x + y; }
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/17/2011 for the course CSI 102 taught by Professor Billcheng during the Spring '11 term at USC.

Page1 / 20

06b_template - Data Structures - CSCI 102 CS102 C+...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online