Function Templates
Completed
Write template <typename T> T maxOf(const vector<T> &v). Use it on a vector of ints and a vector of strings read from input.
Input
Line 1: n then n ints. Line 2: m then m words.
Output
Two lines.
Example
Input
4 3 -1 42 7 3 pear apple zebra
Output
42 zebra
Editor
C++
Hints
The compiler generates a version of the template for each type you use.
Solution explanation
Templates give you generic code with no runtime cost.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
T maxOf(const vector<T> &v) {
T best = v[0];
for (const T &x : v) {
if (best < x) best = x;
}
return best;
}
int main() {
int n, m;
cin >> n;
vector<int> nums(n);
for (int &x : nums) cin >> x;
cin >> m;
vector<string> words(m);
for (auto &w : words) cin >> w;
cout << maxOf(nums) << "\n" << maxOf(words) << "\n";
return 0;
}