Created
February 22, 2017 15:24
-
-
Save pkarneliuk/7daece1b095f2322eefe5009ee4c6c25 to your computer and use it in GitHub Desktop.
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
// 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; | |
} |
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
40 min