Skip to content

Instantly share code, notes, and snippets.

@sivabudh
Created August 23, 2015 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivabudh/5e3ffb681e7443692583 to your computer and use it in GitHub Desktop.
Save sivabudh/5e3ffb681e7443692583 to your computer and use it in GitHub Desktop.
#include <QDebug>
int main(int argc, char** argv) {
// Original sentence
QString const sentence = "this test of is a a this test phrase of is a of a of a test";
qDebug() << "\nTest sentence for histogram is:\n\t" << sentence << "\n\n";
// Split the sentence
QStringList const words = sentence.split(" ");
// Count word frequencies
QMap<QString, uint> frequencies;
for(auto w : words) { frequencies[w] += 1; }
// Copy hash into a sortable container: a list
typedef QPair<QString,uint> Pair;
QList<Pair> sortedFrequencies;
QMapIterator<QString, uint> iter(frequencies);
while(iter.hasNext()){
iter.next();
sortedFrequencies.push_back(Pair(iter.key(),iter.value()));
}
// Sort the list by values, descending
std::sort(sortedFrequencies.begin(), sortedFrequencies.end(), [](Pair const & left_, Pair const & right_ ){
return left_.second > right_.second;
});
// Print out values
qDebug() << "\nFrequency table of sentence is:\n\n";
for(auto const value : sortedFrequencies) {
qDebug() << QString("%1, count = %2")
.arg(value.first)
.arg(value.second);
}
qDebug() << "\nC++ program is DONE.\n";
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment