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
List some of the static data structures in C?
Define recursion in c.
What is function pointer c?
Explain what is a static function?
Explain about C function prototype?
What are the different types of C instructions?
How do you list a file’s date and time?
What is void pointers in c?
A SIMPLE PROGRAM OF GRAPHICS AND THEIR OUTPUT I WANT SEE WAHAT OUTOUT OF GRAPHICS PROGRAM
Do you know pointer in c?
Write a Program to find whether the given number or string is palindrome.
What are the two types of functions in c?
all c language question
How are 16- and 32-bit numbers stored?
What is c preprocessor mean?