Frequency Word
/***
17.9 Design a method to find the frequency of occurrences of any given word in a book.
IDEA: map a book in a hash table or a map. key is word and value is the frequency
***/
#include<iostream>
#include<fstream>
#include<map>
#include<string>
using namespace std;
map<string, int> mapbook(char *book) {
ifstream mybook(book);
string str;
map<string, int> dic;
map<string, int> :: iterator it;
while(mybook.good()) {
mybook>>str;
it = dic.find(str);
if(it != dic.end()) {
it->second += 1;
} else {
dic.insert(pair<string, int>(str, 1));
}
}
return dic;
}
int lookup(string word, char *book) {
map<string, int> dic;
dic = mapbook(book);
if(dic.count(word)) return dic[word];
else return 0;
}
Comments
Post a Comment