lecture36-apr28 - Lecture 36 Announcements Assignment 7...

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

View Full Document Right Arrow Icon
1 Lecture 36 Announcements • Assignment 7 – Q&A • Exam 3 in 1 week • Topics of the day – Generics (aka templates) – STL Overview – material not in the book, see http://www.cppreference.com Or google C++ STL tutorial Provides a suite of common generic data structures for managing collections of elements Provide support for component-based OOP Generics car selectionSort – from previously void selectionSort ( double array [ ], int size) { // this function sorts the given array into descending order int max; // will hold the index of the largest value found for (int i=0; i < size; i++) { max = findMaximum (array, i, size); swap(array, i, max); } } int findMaximum ( double array [ ], int i, int size) { // this function returns the index of the largest value in array int j, max = i; for (j= i + 1; j < size; j++) if (array[j] > array[max]) max =j; return max; } void swap ( double array [ ], int i, int j) { // this function swaps the 2 values at positions i and j in array double temp = array[i]; array[i] = array[j]; array[j] = temp; } What if we could parameterize these functions with a generic data type (say T ) instead of using double ? Template Function Syntax template function syntax includes the keyword template followed by a non-empty list of formal types enclosed in angle brackets, followed by the function definition. In the argument list, each type is preceded by the keyword typename , and types are separated by commas. template <typename T, typename U, typename V, . ..> selectionSort – from previously void selectionSort ( T array [ ], int size) { // this function sorts the given array into descending order int max; // will hold the index of the largest value found for (int i=0; i < size; i++) { max = findMaximum (array, i, size); swap(array, i, max); } } int findMaximum ( T array [ ], int i, int size) {// this function returns the index of the largest value in array int j, max = i; for (j= i + 1; j < size; j++) if (array[j] > array[max]) max =j; return max; } void swap ( T array [ ], int i, int j) { // this function swaps the 2 values at positions i and j in array T temp = array[i]; array[i] = array[j]; array[j] = temp; } template <typename T > selectionSort – calling fcn // calling without generic functions int main ( ) { int arraysize; double myArray [25]; // assume that myArray values are filled in here
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

lecture36-apr28 - Lecture 36 Announcements Assignment 7...

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

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