Write a function template maxOf(a, b) that returns the larger of two values of the same type. main reads two whole numbers, two decimal numbers and two words, and prints the larger of each pair (for words: the one that comes later in dictionary order).
What to build
A function template that returns the larger of two values.
Requirements
- Write one template, not three separate functions.
- Use only
<to compare. - Use it for whole numbers, decimal numbers and words.
Input
Three lines: two whole numbers, two decimal numbers, two words.
Output
Three lines: the larger whole number, the larger decimal number, the later word.
Constraints
The numbers fit in int and double, and the words have no spaces.
Example
Input:
3 9
2.5 1.5
apple banana
Output:
9
2.5
banana
Why it works
The compiler makes a separate version of the template for int, double and string. All three types support <, so the same code works for each.
Examples
3 9 2.5 1.5 apple banana
9 2.5 banana
-4 -8 0.1 0.2 zebra ant
-4 0.2 zebra
Hints
Hint 1
template <typename T> T maxOf(T a, T b) { return a < b ? b : a; }
Hint 2
The same template works for int, double and string, because all three have <.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return a < b ? b : a;
}
int main() {
int a, b;
double x, y;
string s, t;
cin >> a >> b >> x >> y >> s >> t;
cout << maxOf(a, b) << endl;
cout << maxOf(x, y) << endl;
cout << maxOf(s, t) << endl;
return 0;
}