Write a template function maxn() that takes as its arguments an array of items of type T and an integer representing the number of elements in the array and that returns the largest item in the array.
The number of elements should take the default value of 10.
The program should include a specialization that takes an array of strings as an argument and returns the longest string. (If there is a tie, the function should return the first one tied for longest.) (See http://www.cplusplus.com/reference/string/string/).
Test the function with an array of ten ints (using the default argument) and an array of four chars. Test the specialization with an array of five strings.
Deliverables:
Given below is the code for the question. Please do rate the answer if it helped. Thank you.
#include <iostream>
using namespace std;
template <class T>
T maxn(T arr[], int n = 10){
T largest = arr[0];
for(int i = 1; i < n; i++){
if(arr[i] > largest)
largest = arr[i];
}
return largest;
}
//specialization for strings
template <>
string maxn(string arr[], int n ){
string largest = arr[0];
for(int i = 1; i < n; i++){
if(arr[i].length() > largest.length())
largest = arr[i];
}
return largest;
}
int main(){
int nums[10] = {2, 4, 1, 5, 9, 1, 0, 6, 8, 7};
char chars[4] = {'N', 'I', 'C', 'E'};
string strs[5] = {"hello", "good", "excellent", "morning",
"beautiful"};
cout << "Largest int = " << maxn(nums) <<
endl;
cout << "Largest char = " << maxn(chars, 4) <<
endl;
cout << "Largest string = " << maxn(strs, 5) <<
endl;
}
Get Answers For Free
Most questions answered within 1 hours.