Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Created August 18, 2014 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/b8bb11fcdaa790a41bc0 to your computer and use it in GitHub Desktop.
Save ivycheung1208/b8bb11fcdaa790a41bc0 to your computer and use it in GitHub Desktop.
CC150 17.9
/* 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