《第十六周实验报告任务3——电子词典》

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:    电子词典                         
* 作    者:       刘江波                      
* 完成日期:    2012     年   6    月   6     日
* 版 本 号:     v.33    

* 对任务及求解方法的描述部分
* 问题描述:

【任务3】电子词典
做一个简单的电子词典。在文件dictionary.txt 中,保存的是英汉对照的一个词典,词汇量近8000 个,
英文、中文释义与词性间用’\t’隔开。建一个表示词条的类Word,Word 类的一个对象可以描述一个词,
类对象数组可以存储词库。将文件中的内容读到对象数组中,由用户输入英文词,显示中文释义。
提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
拓展1(选做):允许用户运行程序后,连续地查词典,直到输入”0000”结束。
拓展2(选做):试着做一个窗口版的电子词典。
拓展3(选做):使这个词典,读入一篇文章,输出其中的所有名词(或动词,或全部实词)。——
搜索引擎用类似的功能,用于筛去虚词,因为并不是所有词都值得索引。 
* 程序头部的注释结束
*/

#include <fstream>   
#include<iostream>   
#include<string>   
using namespace std;  
  
//定义单词类 
class Word  
{  
public:  
    void set(string e, string c, string wc);  //向词库中置值时使用
    void display();  
	string get_english();//获取对象中的english
private:  
    string english;  
    string chinese;  
    string word_class;  
};  
  
void Word::set(string e, string c, string wc)  
{  
    english=e;  
    chinese=c;  
    word_class=wc;  
}  
  
void Word::display()  
{  
    cout<<english<<'\t'<<word_class<<'\t'<<chinese<<endl<<endl;  
}  
string Word::get_english()
{
	return english;
}

int BinSeareh(int low, int high, Word *w, string k);  
  
int main( )  
{  
    Word words[8000];   
    string e,c,wc;      
    string key;       
    int wordsNum=0;  //词库中词数   
  
    //将文件中的数据读入到对象数组中   
    ifstream infile("dictionary.txt",ios::in);  //以输入的方式打开文件   
    if(!infile)       //测试是否成功打开   
    {  
        cerr<<"open error!"<<endl;  
        exit(1);  
    }  
    while (!infile.eof())  
    {  
        infile>>e>>c>>wc;  
        words[wordsNum].set(e, c, wc);  
        ++wordsNum;  
    }  
  
    //输入待查关键词并用二分查找法进行查询   
    do  
    {  
        cout<<"请输入待查询的关键词(英文):(输入“0000”时结束:)"<<endl;  
        cin>>key;  
        if (key!="0000")  
        {  
            int low=0,high=wordsNum-1;  //置当前查找区间上、下界的初值   
            int index=BinSeareh(low, high, words, key);  
            if (index == -1)  
                cout<<"查无此词!"<<endl<<endl;  
            else  
                words[index].display();  
        }  
    }  
    while(key!="0000");  
    cout<<"欢迎再次使用!"<<endl<<endl;  
    system("pause");  
    return 0;  
}  
  
int BinSeareh(int low, int high, Word *w, string k)  
{  
    int mid;  
    while(low<=high)  
    {   
        mid=(low + high) / 2;  
        if(w[mid].get_english()==k)  //将中间对象中的english与要查找的词进行比较
        {  
            return mid; //查找成功返回   
        }  
        if(w[mid].get_english()>k)  
            high=mid-1; //继续在w[low..mid-1]中查找   
        else  
            low=mid+1; //继续在w[mid+1..high]中查找   
    }  
    return -1; //当low>high时表示查找区间为空,查找失败   
}  


《第十六周实验报告任务3——电子词典》_第1张图片

总结:

二分法要求:

1.必须采用顺序存储结构 2.必须按关键字大小有序排列。

 

 

你可能感兴趣的:(String,搜索引擎,System,存储,Class,任务)