To measure the number of occurrences of all different words in an article, the main steps are as follows:
(1) create a structure with a count
Class Words {public: Words (string str) {count = 1; word = str; next = NULL;} int count; // The number of occurrences of string word; words * next ;};
(2) It is convenient to find the same word. Each time you need to search and compare in the existing word library, you can use the data structure of the linked list. Each new word is added to the end of the linked list; if the word is the same, the word count is increased by 1.
Class WordList {public: void AddWord (string word); // Add the word bool WordExist (string word); // determine whether the word exists void WordPrint (); int getLength () {return length;} // int getTotal () {return total;} // enter the total number of words WordList ();~ WordList (); private: Words * first; Words * last; int length; int total ;};
The implementation of member functions is as follows:
WordList: WordList () {first = new Words (""); first-> next = NULL; last = first; length = 0; total = 0;} WordList ::~ WordList () {Words * p = first; Words * q; while (p! = NULL) {q = p; p = p-> next; delete q ;}} void WordList: AddWord (string word) {if (! WordExist (word) // the word does not exist {Words * node = new Words (word); // create a word class named "word" last-> next = node; last = node; last-> next = NULL; length ++ ;}} bool WordList: WordExist (string word) {Words * p = first-> next; total ++; while (p! = NULL) {if (p-> word = word) {p-> count ++; return true;} p = p-> next;} return false ;} void WordList: WordPrint () {cout <
Next; for (int I = 0; I
Word; int max = p-> count; p = p-> next; cout <
(3) read text, pick words and put them into strings, and perform statistical processing.
Class Text {string txt; WordList mywords; public: void PutIn (); void PutOut (); void Run () ;}; void Text: PutIn () {ifstream file ("in.txt"); if (! File) {cout <"cannot open! "<
The main function is
void main(){ Text mytest; mytest.PutIn(); mytest.Run(); mytest.PutOut();}
Of course, this process is annoying. We can use the map container in STL to implement it.
#include
#include
#include
#include
#include
#include #include
#include
#include
#include
#include
#include
using namespace std;int main (){map
mp;map
:: iterator it;printf("input text(line with only # for end):\n");string s;while(cin >> s && s!="#"){mp[ s ] ++;}cout << "word\ttime" << endl;for(it=mp.begin(); it!=mp.end(); ++it){cout << it->first << "\t" << it->second << endl;}system("pause");return 0;}
Much simpler!