-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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