二叉查找树(二)--简单的信息检索程序

来源:互联网 发布:php数组查找字符串 编辑:程序博客网 时间:2024/06/05 09:37

 继续总结二叉查找树的学习,上篇中最后的测试代码为了简单使用的是整形,那么这篇文章要贴出来的是一个信息检索程序。它要做的就是给定一个文本,找出其中用了哪些不同的词以及每个词使用了多少次。最后的测试数据是截取马丁路德金<I have a dream>的前一部分,自己把里面的标点符号都去了。

这里主要用到两个函数update和print他们的作用就不用说了大家一看就懂大笑

void update(Word &word, Search_tree<Word> &structure);void print(Word &structure);

但是要定义自己的结构体代码如下:

struct Word{string data;int count;Word(){count = 0; data = " ";};Word& operator = (const Word& str){this->data = str.data; this->count++; return *this;}friend bool operator == (const Word& str1, const Word& str2){return(strcmp(str1.data.c_str(), str2.data.c_str())==0);}friend bool operator > (const Word& str1, const Word& str2){return(strcmp(str1.data.c_str(), str2.data.c_str())>0);}friend bool operator < (const Word& str1, const Word& str2){return(strcmp(str1.data.c_str(), str2.data.c_str())<0);}};
从上面的代码中可以看到主要是一些操作符的重载,对于二元操作符使用friend和不使用friend之间的最大区别就是:不使用friend时默认会传递this指针比如上面的operator =,使用friend的话就需要传递两个参数。

关于operator = 函数要注意两点:

        (1)返回Word& 的目的是为了实现多级赋值,例如 Word a,b,c; a=b=c; 当然也可以直接是 void 那么就只能单级赋值了,如a=b;c=b;

        (2)this->count++的作用就是为了实现上面说的统计次数的作用,因为在插入数据是会发生赋值操作,在找的相同数据时也会发生赋值操作,这样做主要是为了不破坏Search_tree和Binary_tree的通用性,当然肯定会有比这跟好的方式,两处赋值操作在Search_tree.cpp的search_and_insert函数和tree_search函数中


最后一点要说的就是二叉查找树键的大小判断是根据字符串的大小来确定的,在测试时并没有统一大小写

#include "Search_word.h"#include <iostream>using namespace std;void update(Word &word, Search_tree<Word> &structure){//如果word在structure中不存在,则把word插入到structure中,并且频率计数加1.如果word已存在 //那么就将它的频率计数加1if(structure.tree_search(word) != success){structure.insert(word);}}void print( Word &word){cout<<word.data<<" "<<word.count<<endl;}
下面是测试代码
#include <iostream>#include <fstream>#include <string>#include "Search_word.h"#include "Search_tree.h"using namespace std;int main(){ifstream ifile;Search_tree<Word> s_tree;ifile.open("11.txt");while(!ifile.eof()){Word ww;ifile>>ww.data;update(ww, s_tree);}ifile.close();s_tree.inorder(print);system("pause");return 0;}
注意:最后采用的是中序遍历的方式来打印的,这样会得到按字母升序排列结果

源代码和测试数据:http://download.csdn.net/detail/mjlsuccess/6523979

原创粉丝点击