家族树的实现

本文介绍了一个使用C++实现的家族树构建与展示程序。该程序通过读取特定格式的文本文件来创建家族树结构,并能够以递归方式展示整个家族成员关系。涉及文件读取、字符串处理及树形结构操作等技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1)函数声明

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct FamilyTreeNode{
    string name;
    vector<FamilyTreeNode * > child;
};
FamilyTreeNode * readFamilyTree(string filename);
void error(string msg);
string getParent(string line);
string getChild(string line);
void insertNode(FamilyTreeNode *&t, string parent, string child);
void showFamily(FamilyTreeNode *t, int order);


2)主函数

int main()
{
    cout << "Hello World!" << endl;
    FamilyTreeNode *t = readFamilyTree("normandy.dat");
    showFamily(t, 0);
    return 0;
}


3)读入文件,输出一个家族树(文件的格式  每行  child:parent   并且第一行必须包含家族树树的根节点, 每一行中的parent必须在前面出现过)

FamilyTreeNode *readFamilyTree(string filename){
    string base = "D:\\QT\\familyTree\\";
    ifstream infile;
    infile.open(base + filename);
    if (infile.fail()){
        error("filename is wrong");
    }
    FamilyTreeNode *t = NULL;
    while(!infile.eof()){
        string line;
        getline(infile, line);
        string parent = getParent(line);
        string child = getChild(line);
        cout << parent << "|||" << child << endl;
        insertNode(t, parent, child);
    }
    return t;
}
void error(string msg){
    cerr << msg;
    exit(EXIT_FAILURE);
}
string getChild(string line){
    string child = "";
    for(int i = 0; i < line.size(); i++){
        if (line[i] == ':')
            break;
        child += line[i];
    }
    return child;
}
string getParent(string line){
    string parent = "";
    int start = -1;
    for(int i = 0; i < line.size(); i++){
        if (line[i] == ':')
            start = 0;
        else if(start == 0){parent += line[i];}
    }
    return parent;
}
void insertNode(FamilyTreeNode *&t, string parent, string child){
    if (t == NULL){
        t = new FamilyTreeNode;
        FamilyTreeNode *c = new FamilyTreeNode;
        t->name = parent;
        c->name = child;
        t->child.push_back(c);
    }
    else if (t->name == parent){
        FamilyTreeNode *c = new FamilyTreeNode;
        c->name = child;
        t->child.push_back(c);
    }
    else{
        for (int i = 0; i < t->child.size(); i++){
            insertNode(t->child[i], parent, child);
        }
    }
}
void showFamily(FamilyTreeNode *t, int order){
    if (t == NULL){
        cout << "there is no family to show.";
    }
    else{
        cout << string(order * 4, ' ') << t->name << endl;
        for (int i = 0; i < t->child.size(); i++){
            showFamily(t->child[i],order + 1);
        }
    }
}



                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值