lect7_3

Lect7_3 - Programming With Arrays Function Templates 1 Programming With Arrays Function Templates Function templates facilitate code reuse They

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

View Full Document Right Arrow Icon

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

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

Unformatted text preview: Programming With Arrays - Function Templates 1 Programming With Arrays - Function Templates Function templates facilitate code reuse. They enable a programmer to write the template for a function only once. The task of producing an actual version of the function is done by the compiler. The searching and sorting functions, we have described before, work only for data values of type int . We can use the typedef feature of C++, and make these func- tions little more flexible, so that they can accept different data types. However, this approach is limited and not as versatile as a template function. Let us begin with an example, which illustrates the limitations of the typedef tech- nique. Consider the following selectionSort function described before. // sorts the array elements of type int in increasing order void selectionSort(int A, int size) { int pass = 0, indexOfSmallest; while (pass < size ) { indexOfSmallest = pass; for ( int i = pass + 1; i < size; i++ ) { if ( A[indexOfSmallest] > A[i] ) indexOfSmallest = i; } // end for int tmp = A[pass]; A[pass] = A[indexOfSmallest]; //swap contents A[indexOfSmallest] = tmp; //swap contents pass++; } // end while } // end function selectionSort Programming With Arrays - Function Templates 2 Instead of sorting an array of type int , suppose that we want to use the selectionSort function for a different type, such as double , or char . Let us use a generic name for the data type, say Type . Then we can modify the selectionSort , and fillArray functions as follows....
View Full Document

This note was uploaded on 04/07/2008 for the course CS 181 taught by Professor Satya during the Fall '08 term at Stevens.

Page1 / 6

Lect7_3 - Programming With Arrays Function Templates 1 Programming With Arrays Function Templates Function templates facilitate code reuse They

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

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