Skip to content

Instantly share code, notes, and snippets.

@d0k
Created June 24, 2010 14:27
Show Gist options
  • Save d0k/451513 to your computer and use it in GitHub Desktop.
Save d0k/451513 to your computer and use it in GitHub Desktop.
sort | uniq -c | sort -n
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
typedef std::map<const std::string, unsigned> map_t;
typedef std::pair<unsigned, const std::string*> pair_t;
typedef std::vector<pair_t> array_t;
static bool comparepair(const pair_t &a, const pair_t &b) {
return a.first > b.first;
}
int main() {
map_t map;
// Gather line counts.
while (std::cin.good()) {
std::string line;
std::getline(std::cin, line);
++map[line];
}
// Make a copy to sort.
array_t array;
array.reserve(map.size());
for (map_t::const_iterator i = map.begin(), e = map.end(); i != e; ++i)
array.push_back(pair_t(i->second, &i->first));
std::sort(array.begin(), array.end(), comparepair);
for (array_t::const_iterator i = array.begin(), e = array.end(); i != e; ++i)
std::cout << i->first << '\t' << *i->second << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment