Created
December 19, 2019 09:45
-
-
Save JustSlavic/14a95de7f91c6f906f43d969eb0c2766 to your computer and use it in GitHub Desktop.
This file contains 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 <functional> | |
#include <algorithm> | |
#include <vector> | |
#include <map> | |
class Dictionary { | |
public: | |
using value_t = std::pair<std::string, size_t>; | |
void push(const std::string& value) { | |
container[value]++; | |
} | |
std::vector<value_t> to_vector() const { | |
std::vector<value_t> result; | |
for (auto&& pair : container) { result.emplace_back(pair); } | |
std::sort(result.begin(), result.end(), cmp); | |
return result; | |
} | |
private: | |
std::function<bool(const value_t&, const value_t&)> | |
cmp = [](const value_t& lhs, const value_t& rhs) -> bool { | |
if (lhs.second == rhs.second) { | |
return lhs.first < rhs.first; | |
} | |
return lhs.second > rhs.second; | |
}; | |
std::map<std::string, size_t> container; | |
}; | |
void apply_to_words(std::istream& input, const std::function<void(std::string&)>& callback) { | |
std::string buffer; | |
while (!input.eof()) { | |
char c = input.get(); | |
if (std::isalpha(c)) { | |
buffer.push_back(std::tolower(c)); | |
} else if (!buffer.empty()) { | |
callback(buffer); | |
buffer.clear(); | |
} | |
} | |
if (!buffer.empty()) { | |
callback(buffer); | |
} | |
} | |
std::vector<Dictionary::value_t> count_words(std::istream& input) { | |
Dictionary dict; | |
apply_to_words(input, [&dict](std::string& word) { dict.push(word); }); | |
return dict.to_vector(); | |
} | |
void push_output(std::ostream& output, const std::vector<Dictionary::value_t>& data) { | |
for (auto&& pair : data) { | |
output << pair.first << " - " << pair.second << std::endl; | |
} | |
} | |
int main(int argc, char** argv) { | |
if (argc < 3) { | |
std::cout << "usage: freq <input file> <output file>" << std::endl; | |
return EXIT_FAILURE; | |
} | |
std::ifstream input(argv[1]); | |
if (!input.is_open()) { | |
std::cerr << "Cannot open the input file"; | |
return 1; | |
} | |
std::ofstream output(argv[2]); | |
if (!output.is_open()) { | |
std::cerr << "Cannot open the output file"; | |
return 1; | |
} | |
auto result = count_words(input); | |
push_output(output, result); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment