Created
August 18, 2014 21:16
-
-
Save ivycheung1208/b8bb11fcdaa790a41bc0 to your computer and use it in GitHub Desktop.
CC150 17.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CC150 17.9 */ | |
// find the frequency of occurrences of any given word in a book | |
#include <iostream> | |
#include <string> | |
#include <unordered_map> | |
#include <fstream> | |
using namespace std; | |
// single query: go through the book to count the occurrences | |
// multiple query: pre-processing, create a freq hash table | |
// assume case sensitive | |
// pre-processor read directly from file | |
unordered_map<string, int> wordFreqCount(string filename) | |
{ | |
ifstream fin(filename); | |
string word; | |
unordered_map<string, int> wordFreq; | |
while (fin >> word) { | |
if (wordFreq.find(word) == wordFreq.end()) | |
wordFreq[word] = 1; | |
else | |
++wordFreq[word]; | |
} | |
fin.close(); | |
return wordFreq; | |
} | |
int main() | |
{ | |
string filename = "book.txt"; | |
unordered_map<string, int> wordFreq = wordFreqCount(filename); | |
string word; | |
cout << "Enter a word to count: "; | |
cin >> word; | |
if (wordFreq.find(word) != wordFreq.end()) | |
cout << wordFreq[word] << endl; | |
else | |
cout << "Not found!" << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment