Skip to content

Instantly share code, notes, and snippets.

@samebchase
Last active August 29, 2015 14:00
Show Gist options
  • Save samebchase/7665b69624ee2b3e1b66 to your computer and use it in GitHub Desktop.
Save samebchase/7665b69624ee2b3e1b66 to your computer and use it in GitHub Desktop.
#include <map>
#include <tuple>
#include <vector>
#include <iostream>
#include <algorithm>
template<typename KeyType>
std::pair<KeyType, std::size_t> most_frequent_element(std::vector<KeyType> elts) {
std::map<KeyType, std::size_t> frequency_table;
auto pair_second_less_than = [](std::pair<KeyType const, std::size_t> const& a,
std::pair<KeyType const, std::size_t> const& b) {
return a.second < b.second;
};
for (auto i : elts) {
frequency_table[i]++;
}
return *std::max_element(frequency_table.begin(),
frequency_table.end(),
pair_second_less_than);
}
int main() {
std::vector<int> test = {1,2,3,4,5,6,3,3,3,3,3,5,5,5,5,5,5,5,5,5,6,7,7,8,3,3,1984};
std::pair<int, std::size_t> entry = most_frequent_element(test);
std::cout << "(" << entry.first << " " << entry.second << ")" << std::endl;
return 0;
}
/*
clang++ frequency.cc -Wall -Werror -pedantic -std=c++11
~/code/exercises/misc/element-frequencies $ ./a.out
(5 10)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment