#include <algorithm> #include <iostream> #include <string> #include <unordered_m
ID: 3547329 • Letter: #
Question
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
// You will need to compile this file via clang++ -std=c++11 frequency.cpp in
// order to make use of the unordered_map and the `auto` keyword
write a program that calculates number of occurrences of unique words given via standard input. The program should print out statistics of the encountered words. The order of the output should be such that the most frequently used words are listed first, and words of the same frequency are sorted according to however strings are sorted by default (lexicographically).
Words can include punctuation and are separated by any form of whitespace. Using cin >> term where term is a string will handle the whitespace issue for you. All comparisons should be case insensitive, meaning that IS, Is, iS, and is should all be counted as one word, is. You will need to write a function that converts a string to its lowercase form. You probably want to use the tolower function to help you with that.
For example echo "ASD aSd asd sdf dfg." | ./a.out should produce the output:
Explanation / Answer
#include <iostream>
#include <map>
#include<algorithm>
using namespace std;
int main(int argc, char* argv[]) {
std::map<std::string, int> wordCount;
std::string word;
for(int i=0;i<argc;i++)
{
word=argv[i];
transform(word.begin(), word.end(), word.begin(), ::tolower);
++wordCount[word];
}
for (std::map<std::string, int>::iterator it = wordCount.begin(); it != wordCount.end(); ++it)
{
cout << it->first <<" : "<< it->second << endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.