Skip to content

Instantly share code, notes, and snippets.

@PlushBeaver
Last active March 3, 2017 19:51
Show Gist options
  • Save PlushBeaver/4f502c80648c97109d472fd501926ab7 to your computer and use it in GitHub Desktop.
Save PlushBeaver/4f502c80648c97109d472fd501926ab7 to your computer and use it in GitHub Desktop.
Входной тест для http://cpp-school.unigine.com без изысков.
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <algorithm>
using namespace std;
void skip_to_word(istream& stream);
string scan_word(istream& stream);
int
main(int argc, char* argv[]) {
if (argc != 3) {
cerr << "Usage: " << argv[0] << " input.txt output.txt\n";
return EXIT_FAILURE;
}
unordered_map<string, size_t> frequences;
ifstream input(argv[1]);
while (input) {
skip_to_word(input);
if (!input) {
break;
}
const auto& word = scan_word(input);
frequences[word]++;
}
ofstream output(argv[2]);
while (!frequences.empty()) {
// VS2013 has no C++14 polymorphic lambdas (for auto parameters).
using Pair = decltype(frequences)::value_type;
auto iterator = max_element(begin(frequences), end(frequences),
[](const Pair& lhs, const Pair& rhs) {
if (lhs.second == rhs.second) {
return lhs.first >= rhs.first;
}
return lhs.second < rhs.second;
});
output << iterator->second << ' ' << iterator->first << '\n';
frequences.erase(iterator);
}
return EXIT_SUCCESS;
}
string
scan_word(istream& stream) {
string word;
while (stream.good()) {
auto symbol = static_cast<char>(stream.get());
if (!isalpha(symbol)) {
stream.unget();
break;
} else {
word += tolower(symbol);
}
}
return word;
}
void
skip_to_word(istream& stream) {
while (stream.good()) {
auto symbol = static_cast<char>(stream.get());
if (isalpha(symbol)) {
stream.unget();
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment