Quick actions

cmd+k|ctrl+k

Navigation

Languages

Naive mode function in C++

Snippet info

Language

Cpp

Visibility

public

Author

atomicptr

Created

2021-10-19T11:57:09.228616Z

Updated

2021-10-19T11:57:21.577874Z

#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;
}
INFO