第十四周项目4:电子词典——二分法查找

来源:互联网 发布:php sql 防注入函数 编辑:程序博客网 时间:2024/06/06 03:46

问题及代码:

/**Copyright (c)2014,烟台大学计算机与控制工程学院*All rights reserved.*文件名称:test.cpp*作    者:陈文青*完成日期:2014年12月1日*版 本 号:v1.0**问题描述:做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结束*程序输入:*程序输出:*/#include <fstream>#include<iostream>#include<cstdlib>#include<string>using namespace std;string e[8000],c[8000]; //英文和中文数组,要由文件中读入int wordsNum=0; //词库中实际的词汇条数int BinSeareh(int low, int high, string k);int main( ){ string key;      //查询关键词//将文件中的数据读入到对象数组中ifstream infile("dictionary.txt",ios::in);  //以输入的方式打开文件if(!infile)       //测试是否成功打开{cerr<<"open error!"<<endl;exit(1);}while (infile>>e[wordsNum]>>c[wordsNum])  //读取成功,则重复从文件中读{++wordsNum;}infile.close();//输入待查关键词并用二分查找法进行查询do{cout<<"请输入要查的词(0000结束):";cin>>key;if (key=="0000")break;else{int low=0,high=wordsNum-1;  //置当前查找区间上、下界的初值int index=BinSeareh(low, high, key);if (index == -1)cout<<"查无此词!"<<endl<<endl;elsecout<<key<<"的中文意思是:"<<c[index]<<endl<<endl;}}while(1);cout<<"欢迎再次使用!"<<endl<<endl;return 0;}//二分查找,结果为所查词在数组中的下标int BinSeareh(int low, int high, string k){int mid;while(low<=high){mid=(low + high) / 2;if(e[mid]==k){return mid; //查找成功返回}if(e[mid]>k)high=mid-1; //继续在e[low..mid-1]中查找elselow=mid+1; //继续在e[mid+1..high]中查找}return -1; //当low>high时表示查找区间为空,查找失败}



知识点总结:

二分法

0 0
原创粉丝点击