Skip to content

Instantly share code, notes, and snippets.

@gibizer
Created December 19, 2019 10:24
Show Gist options
  • Save gibizer/76f61b04fbe59bad7cdb96cc8288fb69 to your computer and use it in GitHub Desktop.
Save gibizer/76f61b04fbe59bad7cdb96cc8288fb69 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <ctype.h>
using namespace std;
bool comparator (pair<string, int>& p1, pair<string, int>& p2) {
return p1.second > p2.second;
}
int main () {
ifstream f;
f.open ("sherlock.txt");
std::unordered_map<string, int> counter;
char c;
string word = "";
while(f) {
f >> noskipws >> c;
if(isalnum(c)) {
word.push_back(tolower(c));
}
else {
if (word != "")
{
counter[word] += 1;
word = "";
}
}
}
f.close();
vector<pair<string, int>> pairs;
for (auto pair : counter) {
pairs.push_back(pair);
}
sort(pairs.begin(), pairs.end(), comparator);
for (auto pair: vector<pair<string, int>>(pairs.begin(), pairs.begin() + 20)) {
cout << pair.first << " " << pair.second << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment