Naive mode function in C++

Run Settings
LanguageC++
Language Version
Run Command
#include <iostream> #include <vector> #include <unordered_map> #include <algorithm> template<typename T> T mode(const std::vector<T>& numbers) { std::unordered_map<T, size_t> frequency; for (auto num : numbers) { if (!frequency[num]) { frequency[num] = 0; } frequency[num]++; } using pair_type = typename decltype(frequency)::value_type; return std::max_element( frequency.begin(), frequency.end(), [](const pair_type& a, const pair_type& b) { return a.second < b.second; } )->first; } int main() { auto numbers = std::vector<int>{5, 3, 7, 3}; std::cout << "mode numbers result: " << mode(numbers) << std::endl; auto strings = std::vector<std::string>{"Hello", "World", "You", "Suck", "World"}; std::cout << "mode strings result: " << mode(strings) << std::endl; return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines