Skip to content
Exercise · Templates · lesson 4 of 11

Exercise: generic max

Write the function template template <typename T> T largest(const std::vector<T>& items) that returns the largest element of the vector. Elements compare with the < operator, so strings are ordered alphabetically, not by length.

  • largest(std::vector<int>{3, 9, 4}) → 9
  • largest(std::vector<double>{2.5, -1.5, 2.75}) → 2.75
  • largest(std::vector<std::string>{"pear", "fig", "plum"}) → "plum"

Constraints: the vector is not empty, T is int, double or std::string, numbers may be negative, and the largest element may repeat.

largest.cpp — cpp
cpp · 7 lines
Ctrl+Enter run · Esc leave editor