{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lect7_3 - Programming With Arrays Function Templates 1...

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

View Full Document Right Arrow Icon
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
Image of page 1

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

View Full Document Right Arrow Icon
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 .
Image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern