General Template Array Function
#include <iostream> #include <array> #include <stdexcept> #include <string> /* * Numeric template parameters are useful to write a function which can * apply to arrays of any size. */ template<typename T, long unsigned int N> T arrmax(const std::array<T,N> &arr) { if(N < 1) throw std::underflow_error("Taking max of empty array"); auto scan = arr.begin(); T ret = *scan++; while(scan < arr.end()) { if(ret < *scan) { ret = *scan; } ++scan; } return ret; } int main() { std::array<int, 10> a1 = { 4, 99, -1, 45, -6, 11, 22, 3, -11, 9 }; std::array<int, 5> a2 = { -10, -5, -3, -8, -17 }; std::array<std::string, 6> a3 = { "This", "is", "a", "very", "short", "sentence" }; std::array<double, 4> a4 = { 20.1, -3.3, 1661.7, 2.2 }; std::cout << arrmax(a1) << " " << arrmax(a2) << " " << arrmax(a3) << " " << arrmax(a4) << std::endl; }