Word frequency: Difference between revisions

Restored original C++ solution
(Restored original C++ solution)
Line 1,425:
=={{header|C++}}==
{{trans|C#}}
<lang cpp>#include <algorithm>
#include <iostream>
#include <fstream>
#include <map>
#include <regex>
#include <string>
#include <vector>
int main() {
using namespace std;
regex wordRgx("\\w+");
map<string, int> freq;
string line;
ifstream in("135-0.txt");
if (!in.is_open()) {
cerr << "Failed to open file\n";
return 1;
}
while (getline(in, line)) {
auto words_itr = sregex_iterator(line.cbegin(), line.cend(), wordRgx);
auto words_end = sregex_iterator();
while (words_itr != words_end) {
auto match = *words_itr;
auto word = match.str();
if (word.size() > 0) {
auto entry = freq.find(word);
if (entry != freq.end()) {
entry->second++;
} else {
freq.insert(make_pair(word, 1));
}
}
words_itr = next(words_itr);
}
}
in.close();
vector<pair<string, int>> pairs;
for (auto iter = freq.cbegin(); iter != freq.cend(); ++iter) {
pairs.push_back(*iter);
}
sort(pairs.begin(), pairs.end(), [=](pair<string, int>& a, pair<string, int>& b) {
return a.second > b.second;
});
cout <pre>< "Rank Word Frequency\n";
cout << "==== ==== =========\n";
int rank = 1;
for (auto iter = pairs.cbegin(); iter != pairs.cend() && rank <= 10; ++iter) {
printf("%2d %4s %5d\n", rank++, iter->first.c_str(), iter->second);
}
return 0;
}</lang>
{{out}}
<pre>Rank Word Frequency
==== ==== =========
1 the 36636
2 of 19615
3 and 14079
4 to 13535
5 a 13527
6 in 10256
7 was 8543
8 that 7324
9 he 6814
10 had 6139</pre>
 
===Alternative===
<lang cpp>#include <algorithm>
#include <cstdio>
Line 1,469 ⟶ 1,539:
return 0;
}</lang>
 
{{out}}
<pre>
<pre>Rank Word Frequency
Rank Word Frequency
==== ==== =========
1 the 3663641093
2 of 1961519954
3 and 1407914943
4 to a 13535 14558
5 to a 1352713953
6 in 1025611219
7 was he 8543 9649
8 that was 7324 8622
9 that he 68147924
10 had it 6139</pre> 6661
</pre>
 
=={{header|Clojure}}==
1,777

edits