I need to create a function that uses a template to partially fill any array and from there search for a value in the array and return its position if found. The program below finds the values for double and int but I do know how to partially fill the array with string or char values. Could someone please help.
//This is the file SearchArrayValue.cpp
//Searches a partially filled array for a number and returns the position of the number if found and
//-1 if not
#include <iostream>
const int SIZE_DECLARED = 10;
template<class T>
void fill_array(T values[], int size, int& number_used);
//Pre condition:
//Post condition: number_used is the number of elements used in the array
//The array is filled with non negative number from values[0] to values[number_used - 1]
//Values will be entered from the keyboard
template<class T>
T search_array(const T values[], int number_used, T search_value);
//Pre condition: array values is filled with <= number_used values
//Post condition: search_value will be searched in the array and if found the position will be returned
//otherwise -1 will be returned
template<class T>
void display_result(T search_value, int search_result);
//Pre condition:
//Post Condition: The position of the searched item in the array is displayed if it was found
//otherwise the appropriate message is returned.
using namespace std;
int main()
{
int number_used;
int int_values[SIZE_DECLARED];
double double_values[SIZE_DECLARED];
char char_values[SIZE_DECLARED];
fill_array(int_values, SIZE_DECLARED, number_used);
fill_array(double_values, SIZE_DECLARED, number_used);
fill_array(char_values, SIZE_DECLARED, number_used);
cin.get();//To keep console window open
cin.get();//To keep console window open
return 0;
}
template<class T>
void fill_array(T values[], int size, int& number_used)
{
T next, search_value;
int index = 0, search_result;
char limit = '.';
cout << "Enter a maximum of " << size << " non negative values: \n";
cout << "(Enter a 0 to stop entry) \n";
cin >> next;
while ((next >= 0)&&(index < size))//||((next != limit)&&(index < size))
{
values[index] = next;
index++;
cin >> next;
}
number_used = index;
cout << "Enter number/char to search for: ";
cin >> search_value;
search_result = search_array(values, number_used, search_value);
display_result(search_value, search_result);
}
template<class T>
T search_array(const T values[], int number_used, T search_value)
{
int index = 0;
bool found = false;
while ((!found) && (index < number_used))
if (search_value == values[index])
found = true;
else
index++;
if (found)
return index;
else
return -1;
}
template<class T>
void display_result(T search_value, int search_result)
{
if (search_result == -1)
cout << "The number " << search_value << " is not in the list" << endl << endl;
else
cout << "The number " << search_value << " was first found at values["
<< search_result << "] of the array" << endl << endl;
}