Skip to content

Instantly share code, notes, and snippets.

@aruslan
Last active February 26, 2017 23:54
Show Gist options
  • Save aruslan/ee803ae6701bb2138a4505f6dd3346c8 to your computer and use it in GitHub Desktop.
Save aruslan/ee803ae6701bb2138a4505f6dd3346c8 to your computer and use it in GitHub Desktop.
locale-unaware solution to cpp test
#include <algorithm>
#include <codecvt>
#include <fstream>
#include <iostream>
#include <locale>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
using namespace std;
struct delims : ctype<wchar_t> {
delims(locale& ru) : ru(ru) {}
bool do_is(mask m, char_type c) const {
return (m & space) ? !isalpha(c, ru) : ctype::do_is(m, c);
}
locale& ru;
};
int main(int argc, const char* argv[]) try {
locale ru(locale(argc>3 ? argv[3] : ""), new std::codecvt_utf8<wchar_t>);
ios_base::sync_with_stdio(false);
wifstream inf;
if (argc>1) inf.open(argv[1]), wcin.rdbuf(inf.rdbuf());
wcin.imbue(locale(ru, new delims(ru)));
wofstream outf;
if (argc>2) outf.open(argv[2]), wcout.rdbuf(outf.rdbuf());
wcout.imbue(ru);
unordered_map<wstring, int> dict;
for(wstring s; wcin >> s;) {
transform(begin(s),end(s), begin(s),
[&ru](auto c) { return tolower(c, ru);});
++dict[s];
}
vector<pair<wstring,int>> result(begin(dict),end(dict));
sort(begin(result),end(result),
[&ru](auto& a, auto& b) {
return tie(b.second,a.first)<tie(a.second,b.first);
});
for(auto& i : result) wcout << i.second << " " << i.first << "\n";
return 0;
} catch(exception& e) { cout << e.what() << endl; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment