Skip to content

Instantly share code, notes, and snippets.

@pkarneliuk
Created February 22, 2017 15:24
Show Gist options
  • Save pkarneliuk/7daece1b095f2322eefe5009ee4c6c25 to your computer and use it in GitHub Desktop.
Save pkarneliuk/7daece1b095f2322eefe5009ee4c6c25 to your computer and use it in GitHub Desktop.
// See http://ideone.com/VvuV4B
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char* argv[]) {
if(argc != 3) return 1;
std::ifstream in(argv[1]);
std::ofstream out(argv[2]);
if(!in || !out) return 1;
//auto& in = std::cin;
//auto& out = std::cout;
std::unordered_map<std::string, std::size_t> freqs;
std::string word;
while(in)
{
auto c = in.get();
if(std::isalpha(c))
{
word.append(1, std::tolower(c));
}
else if(!word.empty())
{
++freqs[word];
word.clear();
}
}
using Item = std::pair<std::string, std::size_t>;
std::vector<Item> results;
results.reserve(freqs.size());
std::move(freqs.begin(), freqs.end(), std::back_inserter(results));
std::sort(results.begin(), results.end(), [](Item& a, Item& b)
{
return a.second > b.second || (a.second == b.second &&
std::lexicographical_compare(a.first.begin(), a.first.end(), b.first.begin(), b.first.end())
);
});
for(auto& item : results)
{
out << item.second << ' ' << item.first << '\n';
}
return 0;
}
@pkarneliuk
Copy link
Author

pkarneliuk commented Feb 22, 2017

40 min

@Sunday111
Copy link

It looks like you need to include cctype to use std::ialpha

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment