Write the program for displaying the ten most frequent words
in a file such that your program should be efficient in all
complexity measures.
Answer Posted / rob lange
Here ya go... It's not pretty...
#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <algorithm>
using namespace std;
int main()
{
string line, file;
stdext::hash_map <std::string, int> words;
stdext::hash_map <std::string, int>::iterator wordsit;
ifstream myfile("example.txt");
// Load file into string
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline(myfile,line);
file.append( line );
file.append( " " );
}
myfile.close();
}
// Parse words into hashmap
char * threadsafe;
char * token = strtok_s((char*)file.c_str(), " ", &threadsafe);
while (token != NULL)
{
wordsit = words.find(token);
if (wordsit != words.end())
++wordsit->second;
else
words[token] = 1;
token = strtok_s(NULL, " ", &threadsafe);
}
// find top 10 threshold value
std::vector < int > topvalue;
int threshold = 0;
for ( wordsit = words.begin(); wordsit != words.end();
wordsit++ )
{
topvalue.push_back( wordsit->second );
}
sort( topvalue.begin(), topvalue.end() );
reverse( topvalue.begin(), topvalue.end() );
if ( topvalue.size() > 10 )
threshold = topvalue[9];
// Search hashmap against value and print word if its
within top10 threshold...
// ties also get printed, so the list might be longer than 10
for ( wordsit = words.begin(); wordsit != words.end();
wordsit++ )
{
if( wordsit->second >= threshold )
cout << wordsit->first << endl;
}
return 0;
}
Is This Answer Correct ? | 5 Yes | 4 No |
Post New Answer View All Answers
Write a programme using structure that create a record of students. The user allow to add a record and delete a record and also show the records in ascending order.
Is main a keyword in c?
Write a program to print fibonacci series without using recursion?
Why isn't it being handled properly?
Explain what is a program flowchart and explain how does it help in writing a program?
What is atoi and atof in c?
What is meant by type casting?
What is an auto variable in c?
Why cant I open a file by its explicit path?
What is scope rule in c?
5 Write an Algorithm to find the maximum and minimum items in a set of ānā element.
void main(int n) { if(n==0) return; main(--n); printf("%d ",n); getch(); } how it work and what will be its output...............it any one know ans plz reply
Do you know the purpose of 'register' keyword?
Write a C/C++ program to add a user to MySQL. The user should be permitted to only "INSERT" into the given database.
How can I implement a delay, or time a users response, with sub-second resolution?