搜索引擎用类似的功能,用于筛去虚词,因为并不是所有词都值得索引。
#include <iostream> using namespace std; #include <fstream> #include <string> class Word { public: void get_cixing(string cixing); void get_chinese(string english); void get_english(string chinese); friend void find_word(Word *t); friend void input_word(Word *t); friend void output_word(Word *t); private: string cixing; string english; string chinese; }; void Word::get_cixing(string cixing) { this->cixing = cixing; } void Word::get_chinese(string english) { this->english = english; } void Word::get_english(string chinese) { this->chinese = chinese; } void input_word(Word *t) { string cixing; string english; string chinese; int i; ifstream inFile("dictionary.txt",ios::in); if(!inFile) { cerr<<"open error!"<<endl; exit(1); } for(i=0;i<8000;++i) { inFile>>chinese; t[i].get_chinese(chinese); inFile>>cixing; t[i].get_cixing(cixing); inFile>>english; t[i].get_english(english); } inFile.close(); } void output_word(Word *t) { string cixing; string english; string chinese; ofstream outFile("dic.txt",ios::out); if(!outFile) { cerr<<"open dic.txt error!"<<endl; exit(1); } for(int i=0;i<8000;++i) { outFile<<t[i].chinese; outFile<<t[i].english; outFile<<t[i].cixing; } outFile.close(); } void find_word(Word *t) { int f=0; int s=7999; int mid=(f+s)/2; string word; cin>>word; while(f<s&&t[mid].english!=word) { if(t[mid].english<word) f=mid+1; if(t[mid].english>word) s=mid-1; mid=f+(s-f)/2; if(t[mid].english==word) { cout<<t[mid].chinese<<endl; cout<<t[mid].cixing<<endl; } } if(t[mid].english!=word) cout<<"没有查到"<<endl; } int main() { Word t[8000]; input_word(t); find_word(t); output_word(t); system("pause"); return 0; }
积累经验:
二分法是个难点,但有问题找百度,对解决问题很有帮助。