In: Computer Science
In C++, write a program that accepts a text file of ASCII words from standard input and store them and the amount of times the word appears in the file in a hash table using external chaining. Then print the words and their counts sorted based on alphabetical order and print them again in decreasing numerical order based on the amount of times the word appears in the file.
Space, tab, and new line all count as space characters.
The first output would look like:
41 1 apple 9 it's 2 lover 2 Purple 7
The second output would look like:
41 1 it's 2 lover 2 Purple 7 apple 9
The required code is given below in case of any doubts you can ask me in comments and please do upvote as it is required for my career.
main.cpp
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef map< string, int> StrIntMap;
bool sortByVal(const pair<string, int> &a, const
pair<string, int> &b)
{
return (a.second < b.second);
}
void countWords( istream& in, StrIntMap& words) {
string s;
while (in >> s) {
++words[s];
}
}
int main() {
ifstream in( "input.txt");
string strArr[1000];
int count = 0;
if (!in)
exit(EXIT_FAILURE);
StrIntMap mymap;
countWords(in, mymap);
cout << "Sorted by keys, is: " << endl;
map<string, int> :: iterator it;
for (it=mymap.begin(); it!=mymap.end(); it++)
{
cout << it->first << ": " << it->second
<< endl;
}
cout << endl;
vector<pair<string, int>> vec;
map<string, int> :: iterator it2;
for (it2=mymap.begin(); it2!=mymap.end(); it2++)
{
vec.push_back(make_pair(it2->first, it2->second));
}
sort(vec.begin(), vec.end(), sortByVal);
cout << "Sorted by value is: " <<
endl;
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i].first <<
": " << vec[i].second << endl;
}
}
input.txt
it's apple lover purple 41
apple
apple
apple
apple
apple
apple
apple
apple
it's
lover purple purple purple
purple
purple
purple
OUTPUT