B树的C++实现

时间:2016-11-19 12:53:00
【文件属性】:
文件名称:B树的C++实现
文件大小:13KB
文件格式:ZIP
更新时间:2016-11-19 12:53:00
B树,C++ 用 C++ 实现的一个 B 树类,有注释,但不知道我写得能不能看明白。使用时先要从类 CDataTypeForBtree 派生一个类出来,在派生类中实现数据比较函数 Compare,数据输出函数 Print。然后在堆上创建一个数据类对象,把地址作为构造函数的参数创建树对象,下面给出一个使用示例。 #include #include #include "DataTypeForBtree.h" #include "BTree.h" struct tree_data { char tid[37]; char tname[63]; unsigned int aid; unsigned int id; }; class CMyDataTypeForBtree : public CDataTypeForBtree { public: virtual void Print(void *key, FILE* fp) { if(NULL == key || NULL == fp) return; struct tree_data* tr = (struct tree_data*)key; fprintf(fp, "%u %u %s %s\n", tr->id, tr->aid, tr->tid, tr->tname); } virtual int Compare(void *p1, void *p2) { if(NULL == p1 || NULL == p2) return (int)(((unsigned int)(~0)) >> 1); //返回一个大点的数表示失败 struct tree_data *tr1, *tr2; tr1 = (struct tree_data*)p1; tr2 = (struct tree_data*)p2; if(tr2->aid != tr1->aid) { return tr1->aid - tr2->aid; } if('\0' == tr1->tid[0] && '\0' == tr2->tid[0]) { return strcmp(tr1->tname, tr2->tname); } return strcmp(tr1->tid, tr2->tid); } CMyDataTypeForBtree() { } virtual ~CMyDataTypeForBtree() { } }; int main(int argc, char* argv[]) { CMyDataTypeForBtree *dt = new CMyDataTypeForBtree; CBTree tree(dt, 5); struct tree_data tr[101] = {{"asd", "4Hero", 1, 1}, {"abc", "Underworld", 1, 0}, {"bac", "Samantha", 1, 2}, {"cass", "Gelka", 1, 3}, {"mark", "Clark", 1, 4}, {"gone", "Woolfy", 1, 5}, {"word", "Production", 1, 6}, {"paper", "Jimpster", 1, 7}, {"Richie", "Hawtin", 1, 8}, {"John", "Matthias", 1, 9}, {"Lou", "Donaldson", 1, 10}, {"Lady", "Alma", 1, 11}, {"Mass", "Slick", 1, 12}, {"Clyde", "Alexander", 1, 13}, //……省略若干,省略部分在下载包里面有 {"", "I'M Not Sayin' Get 'Er Done, But Don'T Just Stand There", 11, 101},}; for(int i = 0; i < 101; i++) { tree.Insert((void*)(tr + i)); } tree.DelKey((void*)(tr + 5)); tree.Traverse(NULL, NULL); tree.DelKey((void*)(tr + 13)); tree.Traverse(NULL, NULL); //输出到标准输出,可以重定向到文件 return 0; }
【文件预览】:
test.cpp
MyDataTypeForBtree.cpp
BTree.h
DataTypeForBtree.h
DataTypeForBtree.cpp
BTree.cpp
MyDataTypeForBtree.h

网友评论