Skip to content

Instantly share code, notes, and snippets.

@hyperair
Forked from alisaifee/suniq.cpp
Last active December 16, 2015 20:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyperair/5489942 to your computer and use it in GitHub Desktop.
Save hyperair/5489942 to your computer and use it in GitHub Desktop.
Rewritten sort | uniq -c | sort -n[r] that works faster than the original.
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <unordered_map>
#include <map>
#include <iterator>
template <typename Iter>
void print (Iter i, Iter end)
{
for (; i != end; std::advance (i, 1))
std::cout << '\t' << i->first << '\t' << i->second << std::endl;
}
void read_lines (std::istream &in, std::unordered_map<std::string, int> &map)
{
std::string buf;
while (std::getline (in, buf)) {
auto iterp = map.insert ({buf, 1});
if (!iterp.second)
++iterp.first->second;
}
}
int main (int argc, char **argv)
{
std::unordered_map<std::string, int> map;
bool reverse = false;
for (char **i = argv + 1; *i; ++i) {
if (std::strcmp (*i, "-r") == 0) {
reverse = true;
continue;
}
std::ifstream f (*i);
read_lines (f, map);
}
if (argc - (int)reverse == 1)
read_lines (std::cin, map);
std::multimap<int, std::string> revmap;
for (const auto &p : map)
revmap.insert ({p.second, p.first});
if (reverse)
print (revmap.rbegin (), revmap.rend ());
else
print (revmap.begin (), revmap.end ());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment