SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Templates
Exercise:
Self-test Exercises
Question:5 | ISBN:9780321531346 | Edition: 7

Question

Display 7.10 shows a function called search, which searches an array for a

specified integer. Give a function template version of search that can be

used to search an array of elements of any type. Give both the function

declaration and the function definition for the template. Hint: It is almost

identical to the function given in Display 7.10.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Function Declaration:

template<class BaseType>

int search(const BaseType a[],

int number_used, BaseType target);

//Precondition: number_used is <= the declared size of a.

//Also, a[0] through a[number_used 1] have values.

//Returns the first index such that a[index] == target,

//provided there is such an index; otherwise, returns 1.

Definition:

template<class BaseType>

int search(const BaseType a[], int number_used,

BaseType target)

{

int index = 0, found = false;

while ((!found) && (index < number_used))

if (target == a[index])

found = true;

else

index++;

if (found)

return index;

else

return 1;

}

0 0

Discussions

Post the discussion to improve the above solution.