Templated function
Implement a findMax template function to find the maximum value in an array.
#include <iostream>
// Implement a template function to find the maximum value in an array
int main() {
int intArray[] = {1, 2, 3, 4, 5};
double doubleArray[] = {1.1, 2.2, 3.3, 4.4, 5.5};
char charArray[] = {'a', 'b', 'c', 'd', 'e'};
// Find and print the maximum values for each array
std::cout << "Maximum in intArray: " << findMax(intArray, 5) << std::endl;
std::cout << "Maximum in doubleArray: " << findMax(doubleArray, 5) << std::endl;
std::cout << "Maximum in charArray: " << findMax(charArray, 5) << std::endl;
return 0;
}
Hint
template <typename T>
T findMax(T arr[], int size);
Answer
findMax is defined to accept an array of any data type and find the maximum value. The template ensures type safety by allowing the same function to operate on different data types without code duplication.
#include <iostream>
template <typename T>
T findMax(T arr[], int size) {
T max = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int intArray[] = {1, 2, 3, 4, 5};
double doubleArray[] = {1.1, 2.2, 3.3, 4.4, 5.5};
char charArray[] = {'a', 'b', 'c', 'd', 'e'};
// Find and print the maximum values for each array
std::cout << "Maximum in intArray: " << findMax(intArray, 5) << std::endl;
std::cout << "Maximum in doubleArray: " << findMax(doubleArray, 5) << std::endl;
std::cout << "Maximum in charArray: " << findMax(charArray, 5) << std::endl;
return 0;
}