使用向量和队列在C ++中构建常规树

时间:2013-03-12 03:45:01

标签: c++ tree queue

对于我的一个类的项目,我需要使用RapidXML从xml文件解析数据并从该数据创建树。我一直在思考如何做好这几天,并且刚刚进入圈内。我真的很感激,如果有人能帮助我在概念上解决这个问题。

每个xml节点都有一个名称属性和子节点,我希望能够访问任何给定节点的沿袭,所以我认为treeNode类将有一个名称变量和一个指向其子节点的向量。到目前为止这听起来是否正确?

一旦我将节点添加到队列中以及如何使用这些节点构建树,我对如何创建节点感到非常困惑。我不确定如何区分哪个节点是哪个节点。这是我解析xml文件的方法。它正确地解析和输出,我只是不知道如何将这些节点存储在树数据结构中。

void oneQueue(xml_node<> *xml)
{
    //Initialize queue
    queue<xml_node<>* > q;

    int nodesInCurrentLevel =1;
    int nodesInNextLevel =0;
    //push the first xml node onto the queue
    q.push(xml);

    while(!q.empty())
    {
        //grab the xml node at the front of the queue
        xml_node<> *currNode = q.front();
        xml_node<> *name = currNode->first_node("name");

        //make a node from the xml node
        Node *node = new Node();
        //IF the name has a value, set the name
        if(name != 0) node->setName(name->value());
        q.pop();
        nodesInCurrentLevel--;

        if(node)
        {
            cout << node->getName() << endl;
            //loop through the children of the node and add to the queue
            for(xml_node<> * species = currNode->first_node("species"); species; species = species->next_sibling())
            {
                q.push(species);
                nodesInNextLevel++;
            }
        }
        if (nodesInCurrentLevel == 0) {
            nodesInCurrentLevel = nodesInNextLevel;
            nodesInNextLevel = 0;
        }
    }
}   

树木对我来说是一个新概念,任何指导都会非常感激。谢谢!

0 个答案:

没有答案