1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <iostream>
#include <algorithm>
#include <type_traits>
#include <stdexcept>
template <typename T>
int mode(const T* values, std::size_t length)
{
static_assert(std::is_integral<T>(), "Type must be an integer.");
if (length <= 0)
return 0;
if (!values)
throw std::invalid_argument{ "Invalid argument passed." };
T number{ values[0] };
T mode{ number };
int count{ 1 };
int count_mode{ 1 };
for (std::size_t i{ 1 }; i < length; ++i)
{
if (values[i] == number)
++count;
else
{
if (count > count_mode)
{
count_mode = count;
mode = number;
}
count = 1;
number = values[i];
}
}
return mode;
}
int main()
{
int values[]{ 2, 1, 1, 5, 7, 1, 2, 3, 3, 1};
std::size_t length{ std::size(values) };
std::sort(std::begin(values), std::end(values));
try
{
auto result{ mode(values, length) };
// If exception is thrown, this won't execute.
std::cout << "mode: " << result << '\n';
}
catch (const std::invalid_argument& e)
{
std::cerr << "Standard exception: " << e.what() << '\n';
}
catch (...)
{
std::cerr << "Unknown Exception caught.\n";
}
}
|