n The C++ template facility provides the ability to define n A generic facility allows code to be written once then
|
|
- Ralf Farmer
- 5 years ago
- Views:
Transcription
1 UCLA PIC 10 B Problem Solvig usig C++ Programmig Ivo Diov, Asst. Prof. i Mathematics, Neurology, Statistics Istructor: Teachig Assistat: Suzae Nezzar, Mathematics Chapter 13 Templates for More Abstractio Uiversity of Califoria, Los Ageles, Summer Templates for More Abstractio Templates for More Abstractio Templates for Algorithm Abstractio g Templates for Fuctios Templates for Data Abstractio g Sytax for Class Templates The C++ template facility provides the ability to defie fuctios ad classes that have parameter that carry type iformatio. This is the geeric facility of C++. A geeric facility allows code to be writte oce the reused with differet types. The classes ad fuctios you will defie i this chapter are much more geeral tha before. It is widely held that a geeric facility is oe of the most importat ideas i programmig Templates for Algorithm Abstractio(1 of 2) Display 13.1 A Fuctio Template // Program to demostrate a fuctio template. #iclude <iostream> usig amespace std; I may fuctios that are writte, the algorithm is more geeral tha the implemetatio. This swap algorithm oly works for it values: void swap ( it & v1, it & v2) { it temp = v1; v1 = v2; v2 = temp; If it is replaced by double, we have aother valid swap routie. I fact, ay type ca be used if the type has a copy costructor ad assigmet defied. Do you see where these are eeded? 5 // Iterchages the values of variable1 ad variable2. void swap_values(t& variable1, T& variable2) { T temp; temp = variable1; variable1 = variable2; variable2 = temp; it mai( ) { it iteger1 = 1, iteger2 = 2; cout << "Origial iteger values are " << iteger1 << " " << iteger2 << edl; swap_values(iteger1, iteger2); cout << "Swapped iteger values are " << iteger1 << " " << iteger2 << edl; char symbol1 = 'A', symbol2 = 'B'; cout << "Origial character values are " << symbol1 << " " << symbol2 << edl; swap_values(symbol1, symbol2); cout << "Swapped character values are " << symbol1 << " " << symbol2 << edl; retur 0; 6 1
2 Templates for Fuctios(1 of 3) Templates for Fuctios(2 of 3) Display 13.1 shows the sytax for a C++ template fuctio, swap_values. The defiitio ad prototype begi with the lie This is called the template prefix. It tells the compiler that the defiitio that follows is a template. It also provides a defiitio for the type parameter T withi the template defiitio. The word class i the template prefix meas type. The template defiitio provides a defiitio of the fuctio for every possible type from which oly the required defiitio is selected. 7 Callig a template fuctio is easy. Write code as if the eeded defiitio were preset. Whe the compiler sees a fuctio call, it searches for a ordiary fuctio ame with a sequece of types i the parameter list. If a defiitio that matches the ame ad parameter list types is foud, that oe is used. If o matches are preset, the the compiler uses a template fuctio defiitio with the correct umber of parameters. If the compiler ca deduce the types of the type parameters, the the compiler uses the template to produce a fuctio with the deduced types. The rules are more complicated, but this is sufficiet i 8 most simple situatios. Templates for Fuctios(3 of 3) Pitfall: Compiler Complicatios We put the template defiitio above before the mai Some compilers do ot allow separate compilatio of fuctio, ad used o prototype. templates. You will likely eed to iclude your template A template fuctio may have a template prototype, but defiitio with your code that uses it. separatig the prototype from the defiitio is ot usually At least the prototype must precede use of the template possible with today's compiler techology. fuctio. The safest strategy is to put the template defiitio i the The safest strategy is to put the template defiitio i the same file where it is used, prior to use of the template. same file where it is used, prior to use of the template. Most template fuctios eed oly oe template Some C++ compilers have pragmas that are ot portable to other compilers. parameter. Some C++ compilers have special, additioal requiremets Use of more tha oe type parameter is always possible. for templates. Read your C++ compiler maual or cosult a Cosider, for example: local expert if you have trouble. You may eed to set template <class T1, class T2> 9 optios or rearrage the order of the template defiitios. 10 Fuctio Template (1 of 2) The fuctio defiitio ad the fuctio prototype for a fuctio template are each prefaced with the followig: template<class Type_Parameter> The prototype (if used) ad defiitio are the the same as ay ordiary fuctio prototype ad defiitio, except that the Type_Parameter ca be used i place of a type. For example, the followig is a prototype for a fuctio template: template<class T1, class T2> void show_stuff( it stuff1, T1 stuff2, T2 stuff3); // Prototype Def.. template<class T1, class T2 > // Fuctio Def void show_stuff( it stuff1, T1 stuff2, T2 stuff3) { cout << stuff1 << edl << stuff2 << edl << stuff3 << edl; Fuctio Template (2 of 2) The fuctio give i this example is equivalet to havig oe fuctio prototype ad oe fuctio defiitio for each possible type ame. The type ame is substituted for the type parameter (which are T1, T2 i the example here.) For istace cosider the followig fuctio call: show_stuff(2, 3.3, ch); Whe this fuctio call is executed, the compiler uses the fuctio defiitio obtaied by replacig T1 with the type ame double, ad T2 by char type. A separate defiitio will be produced for each differet type for which you use the template, but ot for ay types you do ot use. Oly oe defiitio should be geerated regardless of the umber of times you use the template. NOTE: Some compilers require special istructios to esure that oly oe copy of the fuctio is geerated. You wo't see that problem i this course. 2
3 Algorithm Abstractio As we saw i our discussio of the swap_values fuctio, there is a very geeral algorithm for iterchagig the values of two variables ad this more geeral algorithm applies to variables of ay type. Usig a fuctio template we were able to express this more geeral algorithm i C++. This is a very simple example of algorithm abstractio. Whe we say we are usig algorithm abstractio we mea that we are expressig our algorithms i a very geeral way so that we ca igore icidetal detail ad cocetrate o the substative part of the algorithm. Fuctio template are oe feature of C++ that supports algorithm abstractio. 13 Programmig Example: A Geeric Sortig Fuctio(1 of 2) Sortig is a applicatio for templates. Nothig i a sort routies that work by swappig depeds o the type except for havig a copy costructor ad a overloaded < operator ad a overloaded assigmet operator. Examiatio of the defiitio of sort from Display 13.1 show that the base type of the array is ever used i ay sigificat way. The fuctio idex_of_smallest also does ot deped o the base type of the array. By replacig several istaces of it by a type parameter, the fuctio sort ca sort a array of ay type provided that type provides the overloaded operators as outlied above. 14 Programmig Example: A Geeric Sortig Fuctio (2 of 2) The behavior of the < operator must be examied. For example, for letters of the alphabet: With a pair of upper case letters or a pair of lower case letters, < works as expected. Letters later i the alphabet are greater (this is our lexicographical orderig). For mixed upper ad lower case letters, ay upper case letter is less tha ay lower case letter, ad coversely, ay lower case letter is greater tha ay upper case letter. The reaso is that for char values, < compares the ASCII ecodig. (Except oly if your computer uses a differet stadard character table like EBCDIC, which oly happes with IBM maiframes ad a very few miicomputers.) 15 Display 13.2 A Geeric Sortig Fuctio (1 of 2) // This is file sortfuc.cpp void swap_values(t& variable1, T& variable2) { T temp; temp = variable1; variable1 = variable2; variable2 = temp; it idex_of_smallest(cost T a[ ], it start_idex, it umber_used) { T mi = a[start_idex]; it idex_of_mi = start_idex; for (it idex = start_idex + 1; idex < umber_used; idex++) if (a[idex] < mi) { mi = a[idex]; idex_of_mi = idex; // mi is the smallest of a[start_idex] through a[idex] retur idex_of_mi; 16 Display 13.2 A Geeric Sortig Fuctio (2 of 2) void sort(t a[ ], it umber_used) { it idex_of_ext_smallest; for(it idex = 0; idex < umber_used - 1; idex++) { // Place the correct value i a[idex]: idex_of_ext_smallest = idex_of_smallest(a, idex, umber_used); swap_values(a[idex], a[idex_of_ext_smallest]); //a[0] <= a[1] <=...<= a[idex] are the smallest of the origial array //elemets. The rest of the elemets are i the remaiig positios. 17 Display 13.3 Usig a Geeric Sortig Fuctio (1 of 2) // Demostrates a geeric sortig fuctio. #iclude <iostream> usig amespace std; // The file sortfuc.cpp defies the followig fuctio: void sort(t a[ ], it umber_used); // Precoditio: umber_used <= declared size of the array a. // The array elemets a[0] through a[umber_used - 1] have values. // Postcoditio: The values of a[0] through a[umber_used - 1] have // bee rearraged so that a[0] <= a[1] <=... <= a[umber_used - 1]. #iclude "sortfuc.cpp it mai( ) { it i; it a[10] = {9, 8, 7, 6, 5, 1, 2, 3, 0, 4; cout << "Usorted itegers:\"; for (i = 0; i < 10; i++) cout << a[i] << " "; cout << edl; sort(a, 10); cout << "I sorted order the itegers are:\"; for (i = 0; i < 10; i++) cout << a[i] << " "; cout << edl; 18 3
4 Display 13.3 Usig a Geeric Sortig Fuctio (2 of 2) double b[5] = {5.5, 4.4, 1.1, 3.3, 2.2; cout << "Usorted doubles:\"; Programmig Tip: How to defie Templates for (i = 0; i < 5; i++) cout << b[i] << " "; cout << edl; sort(b, 5); cout << "I sorted order the doubles are:\"; 1. We created the template for Display 13.2 by writig a ordiary fuctio that sorts for base type it. 2. We created the template by replacig the base type of for (i = 0; i < 5; i++) cout << b[i] << << edl; the array with type parameter T. char c[7] = {'G', 'E', 'N', 'E', 'R', 'I', 'C'; cout << "Usorted characters:\"; 3. This process has two advatages: for (i = 0; i < 7; i++) cout << c[i] << << edl; 1. The ordiary fuctio is cocrete which is easier to sort(c, 7); visualize. cout << "I sorted order the characters are:\"; for (i = 0; i < 7; i++) cout << c[i] << << edl; retur 0; You are dealig with fewer details. You do't have to worry about template sytax rules Templates for Data Abstractio Sytax for Class Templates Sytax for Class Templates(1 of 3) class template sytax requires a template prefix: Oce the class template is defied, you ca defie objects of the template class: where T is a type ame. As i fuctio templates, T ca be a built-i type or a class. Pair<it> score1; Example: Pair<char> seats1; class Pair Usig the parameterized costructor { Pair<it> score2(1,2); public: Pair( ( ); Pair<char> seats2('a', 'B ); Pair(T first_value, T secod_value); void set_elemet(it positio, T value); T get_elemet(it positio) cost; The Objects are like ay other objects. We apply private: the member fuctio set_elemet: T first; score1.set_elemet(1,3); T secod; ; 21 score1.set_elemet(2,0); 22 Sytax for Class Templates(2 of 3) Sytax for Class Templates(3 of 3) Note the class ame Pair<T> is used for scope resolutio, ot just Pair. // Uses iostream ad cstdlib: void Pair<T>::set_elemet( set_elemet(it positio, T value) { if (positio = 1) first = value; else if (positio = 2) secod = value; else { cout << "Error: Illegal pair positio.\"; "; exit(1); 23 The costructors are: Pair<T>::Pair( ) { //I the default costructor,, you first = T( ); //ca iitialize first ad secod secod = T( ); //usig the default T object //costructor, whatever it may be. Pair<T>::Pair(T first_value, T secod_value) { first = first_value; secod = secod_value; As i the member fuctio, the class ame for scope resolutio must be Pair<T>, ot just Pair. 24 4
5 Class Template Sytax (1 of 2) The class defiitio ad the defiitios of the member fuctios are prefaced with the followig: template<class Type_Parameter> The class ad member fuctio defiitios are the the same as for ay ordiary class except that Type_Parameter ca be used i p lace of a type. For example, the followig is the begiig of a class template defiitio: class Pair { public: Pair( ); Pair( T first_value, T secod_value);... ; 25 Class Template Sytax (2 of 2) Member fuctios ad overloaded operators are the defied as fuctio templates. For example, the defiitio of the two argumet costructor for the above sample class template would begi: Pair<T>::Pair(T first_value, T secod_value) { Type Defiitios You ca specialize a class template by givig a type argumet to the class ame as i the followig example: Programmig Example: A Array Class Pair<it> Display 13.4 cotais the iterface for a class template amed The specialized class ame, like Pair<it>, ca the be used just like List whose objects are lists of a user specified type which may be ay class ame. It ca be used to declare objects or to specify the type built-i or user defied. of a formal parameter. Display 13.5 cotais a demostratio program that uses the List You ca defie a ew class type ame that has the same meaig as a template class. The purpose is to illustrate sytax. specialized class template ame, such as Pair<it>. The sytax for Display 13.6 cotais the implemetatio of the List class such a defied class type ame is: template. The data is stored iterally as a dyamic array. typedef Class_Name<Type_argumet> New_Type_Name; Members provided are the default costructor, a destructor, For example: legth, add, full, ad erase. typedef Pair<it> PairOfIt; Notice the overloaded isertio operator (<<), whichweuseto The typeame PairOfIt ca the be used to declare objects of type output a object of template class List. Pair<it> as i this example: Whe we specify a parameter of List class type i a template PairOfIt pair1, pair2; fuctio, whether a member or stadaloe, we use List<T>. The type ame PairOfIt ca also be used to specify the type of a Whe we specify a template List parameter type that holds it formal parameter values, the type is specified as List<it>. 28 Display 13.4 Iterface for the Class Template List (1 of 2) // FILE: list.h. // This is the INTERFACE for the class List. List objects ca hold items of ay // type where operators << ad = are defied. All the items o ay oe list must // be of the same type. Declare a list of up to max items of type Type_Name as: // List<Type_Name> the_object(max); #ifdef LIST_H #defie LIST_H #iclude <iostream> usig amespace std; amespace savitchlist { class List { public: List(it max); // Iitializes the object to a empty list that ca // holduptomaxitemsoftypet. ~List( ); // Returs all the dyamic memory used by the object to the heap. it legth( ) cost; // Returs the umber of items o the list. 29 Display 13.4 Iterface for the Class Template List (2 of 2) // FILE: list.h. void add(t ew_item); // Precoditio: The list is ot full. // Postcoditio: The ew_item has bee added to the list. itfull()cost; // Returs true if the list is full. void erase( ); // Removes all items from the list so that the list is empty. fried ostream& operator <<(ostream& outs, cost List<T>& the_list); // Overloads the << operator so it ca be used to output the cotets // of the list. The items are output oe per lie. // Precoditio: If outs is a file output stream, the outs has already // bee coected to a file. private: T *item; //poiter to the dyamic array that holds the list. it max_legth; //max umber of items allowed o the list. it curret_legth; //umber of items curretly o the list. ; // savitchlist #edif //LIST_H 30 5
6 Display 13.5 Program usig the List class Template // Program to demostrate use of the class template List. #iclude <iostream> #iclude "list.h" #iclude "list.cxx" usig amespace std; usig amespace savitchlist; it mai( ) { List<it> first_list(2); first_list.add(1); first_list.add(2); cout << "first_list = \" << first_list; List<char> secod_list(10); secod_list.add('a'); secod_list.add('b'); secod_list.add('c'); cout << "secod_list = \" << secod_list; retur 0; 31 Display 13.6 Implemetatio of List (1 of 3) // FILE: list.cpp This is the IMPLEMENTATION of the class template List. // The iterface for this class is list.h. #ifdef LIST_CXX #defie LIST_CXX #iclude <iostream> #iclude <cstdlib> #iclude "list.h" //This is ot eeded whe used as we are usig this file, //but the #ifdef i list.h makes it safe. usig amespace std; amespace savitchlist { // Uses cstdlib: List<T>::List(it max) { max_legth = max; curret_legth = 0; delete [ ] item; item = ew T[max]; if (item == NULL) { cout << "Error: Isufficiet memory.\"; exit(1); 32 Display 13.6 Implemetatio of List (2 of 3) List<T>::~List( ) { delete [ ] item; it List<T>::legth( ) cost { retur (curret_legth); Display 13.6 Implemetatio of List (3 of 3) it List<T>::full( ) cost { retur (curret_legth >= max_legth); void List<T>::erase( ) { curret_legth = 0; //Uses iostream ad cstdlib: void List<T>::add(T ew_item) { if(full()) { cout << "Error: addig to a full list.\"; exit(1); else { item[curret_legth] = ew_item; curret_legth = curret_legth + 1; 33 //Uses iostream: ostream& operator <<(ostream& outs, cost List<T>& the_list) { for (it i = 0; i < the_list.curret_legth; i++) outs << the_list.item[i] << edl; retur outs; // savitchlist #edif // LIST.CPP Notice that we have eclosed all the template // defiitios i #ifdef... #edif. 34 Chapter Summary Usig fuctio templates you ca defie fuctios that have a parameter for a type. Usig class templates you ca defie a class with a type parameter for sub-parts of the class. 35 6
" Templates for Functions. ! Templates for Data Abstraction. "Syntax for Class Templates. ! This swap algorithm only works for int values:
UCLA Stat 130D Statistical Computing and Visualization in C++ Templates for More Abstraction Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 2004
More informationChapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4
More informationChapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3
More informationChapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig
More informationCOSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1
COSC 1P03 Ch 7 Recursio Itroductio to Data Structures 8.1 COSC 1P03 Recursio Recursio I Mathematics factorial Fiboacci umbers defie ifiite set with fiite defiitio I Computer Sciece sytax rules fiite defiitio,
More informationChapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,
More informationChapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs
More informationChapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19
CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.
More informationFrom last week. Lecture 5. Outline. Principles of programming languages
Priciples of programmig laguages From last week Lecture 5 http://few.vu.l/~silvis/ppl/2007 Natalia Silvis-Cividjia e-mail: silvis@few.vu.l ML has o assigmet. Explai how to access a old bidig? Is & for
More informationCS 11 C track: lecture 1
CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to
More informationLecture 5. Counting Sort / Radix Sort
Lecture 5. Coutig Sort / Radix Sort T. H. Corme, C. E. Leiserso ad R. L. Rivest Itroductio to Algorithms, 3rd Editio, MIT Press, 2009 Sugkyukwa Uiversity Hyuseug Choo choo@skku.edu Copyright 2000-2018
More informationLecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming
Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis
More information. Written in factored form it is easy to see that the roots are 2, 2, i,
CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or
More informationData Structures and Algorithms Part 1.4
1 Data Structures ad Algorithms Part 1.4 Werer Nutt 2 DSA, Part 1: Itroductio, syllabus, orgaisatio Algorithms Recursio (priciple, trace, factorial, Fiboacci) Sortig (bubble, isertio, selectio) 3 Sortig
More informationwhy study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.
Chapter 5 Sortig IST311 - CIS65/506 Clevelad State Uiversity Prof. Victor Matos Adapted from: Itroductio to Java Programmig: Comprehesive Versio, Eighth Editio by Y. Daiel Liag why study sortig? Sortig
More informationCMPT 125 Assignment 2 Solutions
CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address
More informationChapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig
More informationChapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms
Chapter 4 Sortig 1 Objectives 1. o study ad aalyze time efficiecy of various sortig algorithms 4. 4.7.. o desig, implemet, ad aalyze bubble sort 4.. 3. o desig, implemet, ad aalyze merge sort 4.3. 4. o
More informationClasses and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1
Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1 The simplest
More informationRecursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:
Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical
More information10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output
File class i Java File Iput ad Output TOPICS File Iput Exceptio Hadlig File Output Programmers refer to iput/output as "I/O". The File class represets files as objects. The class is defied i the java.io
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig
More informationSorting in Linear Time. Data Structures and Algorithms Andrei Bulatov
Sortig i Liear Time Data Structures ad Algorithms Adrei Bulatov Algorithms Sortig i Liear Time 7-2 Compariso Sorts The oly test that all the algorithms we have cosidered so far is compariso The oly iformatio
More informationWORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:
Worked Example 7.1 Producig a Mass Mailig 1 WORKED EXAMPLE 7.1 Producig a Mass Mailig We wat to automate the process of producig mass mailigs. A typical letter might look as follows: To: Ms. Sally Smith
More informationChapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 16 Templates Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Function Templates Syntax, defining Compiler complications Class Templates Syntax Example: array template
More informationPriority Queues. Binary Heaps
Priority Queues Biary Heaps Priority Queues Priority: some property of a object that allows it to be prioritized with respect to other objects of the same type Mi Priority Queue: homogeeous collectio of
More informationRecursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames
Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of
More informationComputers and Scientific Thinking
Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput
More informationtop() Applications of Stacks
CS22 Algorithms ad Data Structures MW :00 am - 2: pm, MSEC 0 Istructor: Xiao Qi Lecture 6: Stacks ad Queues Aoucemets Quiz results Homework 2 is available Due o September 29 th, 2004 www.cs.mt.edu~xqicoursescs22
More informationCOP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall 2016
More informationExamples and Applications of Binary Search
Toy Gog ITEE Uiersity of Queeslad I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We
More informationLower Bounds for Sorting
Liear Sortig Topics Covered: Lower Bouds for Sortig Coutig Sort Radix Sort Bucket Sort Lower Bouds for Sortig Compariso vs. o-compariso sortig Decisio tree model Worst case lower boud Compariso Sortig
More information3. b. Present a combinatorial argument that for all positive integers n : : 2 n
. b. Preset a combiatorial argumet that for all positive itegers : : Cosider two distict sets A ad B each of size. Sice they are distict, the cardiality of A B is. The umber of ways of choosig a pair of
More informationUniversity of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures
Uiversity of Waterloo Departmet of Electrical ad Computer Egieerig ECE 250 Algorithms ad Data Structures Midterm Examiatio ( pages) Istructor: Douglas Harder February 7, 2004 7:30-9:00 Name (last, first)
More informationn Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.
Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,
More informationcondition w i B i S maximum u i
ecture 10 Dyamic Programmig 10.1 Kapsack Problem November 1, 2004 ecturer: Kamal Jai Notes: Tobias Holgers We are give a set of items U = {a 1, a 2,..., a }. Each item has a weight w i Z + ad a utility
More informationAnalysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis
Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems
More informationthe beginning of the program in order for it to work correctly. Similarly, a Confirm
I our sytax, a Assume statemet will be used to record what must be true at the begiig of the program i order for it to work correctly. Similarly, a Cofirm statemet is used to record what should be true
More informationThreads and Concurrency in Java: Part 1
Cocurrecy Threads ad Cocurrecy i Java: Part 1 What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.
More informationn n B. How many subsets of C are there of cardinality n. We are selecting elements for such a
4. [10] Usig a combiatorial argumet, prove that for 1: = 0 = Let A ad B be disjoit sets of cardiality each ad C = A B. How may subsets of C are there of cardiality. We are selectig elemets for such a subset
More informationChapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 6 I/O Streams as a Itroductio to Objects ad Classes Overview 6.1 Streams ad Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams ad Basic File I/O I/O Streams I/O refers
More informationThreads and Concurrency in Java: Part 1
Threads ad Cocurrecy i Java: Part 1 1 Cocurrecy What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.
More informationCS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1
CS200: Hash Tables Prichard Ch. 13.2 CS200 - Hash Tables 1 Table Implemetatios: average cases Search Add Remove Sorted array-based Usorted array-based Balaced Search Trees O(log ) O() O() O() O(1) O()
More informationAlgorithm. Counting Sort Analysis of Algorithms
Algorithm Coutig Sort Aalysis of Algorithms Assumptios: records Coutig sort Each record cotais keys ad data All keys are i the rage of 1 to k Space The usorted list is stored i A, the sorted list will
More informationCHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs
CHAPTER IV: GRAPH THEORY Sectio : Itroductio to Graphs Sice this class is called Number-Theoretic ad Discrete Structures, it would be a crime to oly focus o umber theory regardless how woderful those topics
More information9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence
_9.qxd // : AM Page Chapter 9 Sequeces, Series, ad Probability 9. Sequeces ad Series What you should lear Use sequece otatio to write the terms of sequeces. Use factorial otatio. Use summatio otatio to
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists
More informationMajor CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70
NOTE:. Attempt all seve questios. Major CSL 02 2. Write your ame ad etry o o every sheet of the aswer script. Time 2 Hrs Max Marks 70 Q No Q Q 2 Q 3 Q 4 Q 5 Q 6 Q 7 Total MM 6 2 4 0 8 4 6 70 Q. Write a
More informationChapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 2 C++ Basics Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 2.1 Variables ad Assigmets 2.2 Iput ad Output 2.3 Data Types ad Expressios 2.4 Simple Flow of Cotrol 2.5 Program
More informationLast Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types
Aoucemets HW9 due today HW10 comig up, will post after class Team assigmet Data abstractio (types) ad cotrol abstractio (parameter passig) Due o Tuesday, November 27 th Last Class Types Type systems Type
More informationMOTIF XF Extension Owner s Manual
MOTIF XF Extesio Ower s Maual Table of Cotets About MOTIF XF Extesio...2 What Extesio ca do...2 Auto settig of Audio Driver... 2 Auto settigs of Remote Device... 2 Project templates with Iput/ Output Bus
More informationCS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016
CS 111: Program Desig I Lecture 15: Objects, Padas, Modules Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 13, 2016 OBJECTS AND DOT NOTATION Objects (Implicit i Chapter 2, Variables,
More informationChapter 17. Templates
Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction 2 17.1 Templates for Algorithm Abstraction 3 Templates for Algorithm Abstraction Function definitions
More informationSolution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:
CS 604 Data Structures Midterm Sprig, 00 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Istructios: Prit your ame i the space provided below. This examiatio is closed book ad closed
More informationCSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.
CSE Notes 8: Sortig (Last updated //8 7:6 PM) CLRS 7.-7., 9., 8.-8. 8.A. QUICKSORT Cocepts Idea: Take a usorted (sub)array ad partitio ito two subarrays such that p q r x y z x y y z Pivot Customarily,
More informationCSC 220: Computer Organization Unit 11 Basic Computer Organization and Design
College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13
CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis
More informationCSE 417: Algorithms and Computational Complexity
Time CSE 47: Algorithms ad Computatioal Readig assigmet Read Chapter of The ALGORITHM Desig Maual Aalysis & Sortig Autum 00 Paul Beame aalysis Problem size Worst-case complexity: max # steps algorithm
More informationCS211 Fall 2003 Prelim 2 Solutions and Grading Guide
CS11 Fall 003 Prelim Solutios ad Gradig Guide Problem 1: (a) obj = obj1; ILLEGAL because type of referece must always be a supertype of type of object (b) obj3 = obj1; ILLEGAL because type of referece
More informationCIS 121. Introduction to Trees
CIS 121 Itroductio to Trees 1 Tree ADT Tree defiitio q A tree is a set of odes which may be empty q If ot empty, the there is a distiguished ode r, called root ad zero or more o-empty subtrees T 1, T 2,
More informationn Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis
Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig
More informationBasic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.
5-23 The course that gives CM its Zip Memory Maagemet II: Dyamic Storage Allocatio Mar 6, 2000 Topics Segregated lists Buddy system Garbage collectio Mark ad Sweep Copyig eferece coutig Basic allocator
More informationLecture 28: Data Link Layer
Automatic Repeat Request (ARQ) 2. Go ack N ARQ Although the Stop ad Wait ARQ is very simple, you ca easily show that it has very the low efficiecy. The low efficiecy comes from the fact that the trasmittig
More informationOnes Assignment Method for Solving Traveling Salesman Problem
Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:
More informationAbstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:
Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values
More informationThe Magma Database file formats
The Magma Database file formats Adrew Gaylard, Bret Pikey, ad Mart-Mari Breedt Johaesburg, South Africa 15th May 2006 1 Summary Magma is a ope-source object database created by Chris Muller, of Kasas City,
More informationAvid Interplay Bundle
Avid Iterplay Budle Versio 2.5 Cofigurator ReadMe Overview This documet provides a overview of Iterplay Budle v2.5 ad describes how to ru the Iterplay Budle cofiguratio tool. Iterplay Budle v2.5 refers
More informationCode Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013
Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of
More information6.854J / J Advanced Algorithms Fall 2008
MIT OpeCourseWare http://ocw.mit.edu 6.854J / 18.415J Advaced Algorithms Fall 2008 For iformatio about citig these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 18.415/6.854 Advaced Algorithms
More informationComputer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.
Computer Sciece Foudatio Exam August, 005 Computer Sciece Sectio A No Calculators! Name: SSN: KEY Solutios ad Gradig Criteria Score: 50 I this sectio of the exam, there are four (4) problems. You must
More informationn Haskell n Syntax n Lazy evaluation n Static typing and type inference n Algebraic data types n Pattern matching n Type classes
Aoucemets Quiz 7 HW 9 is due o Friday Raibow grades HW 1-6 plus 8. Please, read our commets o 8! Exam 1-2 Quiz 1-6 Ay questios/cocers, let us kow ASAP Last Class Haskell Sytax Lazy evaluatio Static typig
More informationCS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions
CS 111: Program Desig I Lecture # 7: First Loop, Web Crawler, Fuctios Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago September 18, 2018 What will this prit? x = 5 if x == 3: prit("hi!")
More informationCS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018
CS 111: Program Desig I Lecture 15: Modules, Padas agai Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago March 8, 2018 PYTHON STANDARD LIBRARY & BEYOND: MODULES Extedig Pytho Every moder
More information27 Refraction, Dispersion, Internal Reflection
Chapter 7 Refractio, Dispersio, Iteral Reflectio 7 Refractio, Dispersio, Iteral Reflectio Whe we talked about thi film iterferece, we said that whe light ecouters a smooth iterface betwee two trasparet
More informationAPPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS
APPLICATION NOTE PACE175AE BUILT-IN UNCTIONS About This Note This applicatio brief is iteded to explai ad demostrate the use of the special fuctios that are built ito the PACE175AE processor. These powerful
More informationHeaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015
Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 201 Heaps 201 Goodrich ad Tamassia xkcd. http://xkcd.com/83/. Tree. Used with permissio uder
More informationEvaluation scheme for Tracking in AMI
A M I C o m m u i c a t i o A U G M E N T E D M U L T I - P A R T Y I N T E R A C T I O N http://www.amiproject.org/ Evaluatio scheme for Trackig i AMI S. Schreiber a D. Gatica-Perez b AMI WP4 Trackig:
More informationArithmetic Sequences
. Arithmetic Sequeces COMMON CORE Learig Stadards HSF-IF.A. HSF-BF.A.1a HSF-BF.A. HSF-LE.A. Essetial Questio How ca you use a arithmetic sequece to describe a patter? A arithmetic sequece is a ordered
More informationOverview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup
Chapter 18 Vectors ad Arrays Bjare Stroustrup Vector revisited How are they implemeted? Poiters ad free store Destructors Iitializatio Copy ad move Arrays Array ad poiter problems Chagig size Templates
More informationOne advantage that SONAR has over any other music-sequencing product I ve worked
*gajedra* D:/Thomso_Learig_Projects/Garrigus_163132/z_productio/z_3B2_3D_files/Garrigus_163132_ch17.3d, 14/11/08/16:26:39, 16:26, page: 647 17 CAL 101 Oe advatage that SONAR has over ay other music-sequecig
More informationData diverse software fault tolerance techniques
Data diverse software fault tolerace techiques Complemets desig diversity by compesatig for desig diversity s s limitatios Ivolves obtaiig a related set of poits i the program data space, executig the
More informationHomework 1 Solutions MA 522 Fall 2017
Homework 1 Solutios MA 5 Fall 017 1. Cosider the searchig problem: Iput A sequece of umbers A = [a 1,..., a ] ad a value v. Output A idex i such that v = A[i] or the special value NIL if v does ot appear
More informationLinked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes
Prelimiaries Liked Lists public class StrageObject { Strig ame; StrageObject other; Arrays are ot always the optimal data structure: A array has fixed size eeds to be copied to expad its capacity Addig
More informationOverview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup
Overview Chapter 20 The STL (cotaiers, iterators, ad algorithms) Bjare Stroustrup www.stroustrup.com/programmig Commo tasks ad ideals Geeric programmig Cotaiers, algorithms, ad iterators The simplest algorithm:
More informationLecture 9: Exam I Review
CS 111 (Law): Program Desig I Lecture 9: Exam I Review Robert H. Sloa & Richard Warer Uiversity of Illiois, Chicago September 22, 2016 This Class Discuss midterm topics Go over practice examples Aswer
More informationWeb OS Switch Software
Web OS Switch Software BBI Quick Guide Nortel Networks Part Number: 213164, Revisio A, July 2000 50 Great Oaks Boulevard Sa Jose, Califoria 95119 408-360-5500 Mai 408-360-5501 Fax www.orteletworks.com
More informationGetting Started. Getting Started - 1
Gettig Started Gettig Started - 1 Issue 1 Overview of Gettig Started Overview of Gettig Started This sectio explais the basic operatios of the AUDIX system. It describes how to: Log i ad log out of the
More informationBezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only
Edited: Yeh-Liag Hsu (998--; recommeded: Yeh-Liag Hsu (--9; last updated: Yeh-Liag Hsu (9--7. Note: This is the course material for ME55 Geometric modelig ad computer graphics, Yua Ze Uiversity. art of
More informationBehavioral Modeling in Verilog
Behavioral Modelig i Verilog COE 202 Digital Logic Desig Dr. Muhamed Mudawar Kig Fahd Uiversity of Petroleum ad Mierals Presetatio Outlie Itroductio to Dataflow ad Behavioral Modelig Verilog Operators
More informationSorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness
9/5/009 Algorithms Sortig 3- Sortig Sortig Problem The Sortig Problem Istace: A sequece of umbers Objective: A permutatio (reorderig) such that a ' K a' a, K,a a ', K, a' of the iput sequece The umbers
More informationThe isoperimetric problem on the hypercube
The isoperimetric problem o the hypercube Prepared by: Steve Butler November 2, 2005 1 The isoperimetric problem We will cosider the -dimesioal hypercube Q Recall that the hypercube Q is a graph whose
More informationCS 111: Program Design I Lecture 16: Module Review, Encodings, Lists
CS 111: Program Desig I Lecture 16: Module Review, Ecodigs, Lists Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 18, 2016 Last time Dot otatio ad methods Padas: user maual poit
More informationGraphs. Minimum Spanning Trees. Slides by Rose Hoberman (CMU)
Graphs Miimum Spaig Trees Slides by Rose Hoberma (CMU) Problem: Layig Telephoe Wire Cetral office 2 Wirig: Naïve Approach Cetral office Expesive! 3 Wirig: Better Approach Cetral office Miimize the total
More informationA graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))
ca see that time required to search/sort grows with size of We How do space/time eeds of program grow with iput size? iput. time: cout umber of operatios as fuctio of iput Executio size operatio Assigmet:
More informationNAG Library Function Document nag_fft_hermitian (c06ebc)
c06 Fourier Trasforms NAG Library Fuctio Documet ag_fft_hermitia () 1 Purpose ag_fft_hermitia () calculates the discrete Fourier trasform of a Hermitia sequece of complex data values. (No extra workspace
More information1.2 Binomial Coefficients and Subsets
1.2. BINOMIAL COEFFICIENTS AND SUBSETS 13 1.2 Biomial Coefficiets ad Subsets 1.2-1 The loop below is part of a program to determie the umber of triagles formed by poits i the plae. for i =1 to for j =
More informationDATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer
Data structures DATA STRUCTURES Static problems. Give a iput, produce a output. Ex. Sortig, FFT, edit distace, shortest paths, MST, max-flow,... amortized aalysis biomial heaps Fiboacci heaps uio-fid Dyamic
More information