C++: The largest of a list

Write one function that works for numbers and for text.

What to build

A function template used with two types.

Requirements

  • Write T largest(const vector<T>& v).
  • Do not change main, which uses it for both int and string.

Input

The first line has n, then n whole numbers. The next line has m, then m words.

Output

Two lines.

Constraints

n and m are from 1 to 100.

Example

Input:

3 1 9 4
2 pear apple

Output:

9
pear

Why it works

The function only needs < to work, and both int and string have it, so one definition serves both.

Examples

Example 1 · Input
3 1 9 4
2 pear apple
Expected output
9
pear
Example 2 · Input
1 -5
1 a
Expected output
-5
a

Hints

Hint 1

Write template <typename T> above the function.

Hint 2

Take the vector by const reference.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <typename T>
T largest(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> a(n);
    for (int& x : a) cin >> x;
    cin >> m;
    vector<string> b(m);
    for (string& s : b) cin >> s;
    cout << largest(a) << endl;
    cout << largest(b) << endl;
    return 0;
}

Lesson: Templates →