在模板的二进制树 [英] Binary-Tree in Template

查看:186
本文介绍了在模板的二进制树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想创建一个代码,它创建一个二叉树,它保存数据,例如ints像1,6,2,10,8和在pop我得到最大的数字,然后它被删除树,并且在推我可以插入一个新的元素。这应该是在一个模板,所以我可以很容易地改变我想要在树中持有的数据类型。现在我得到了树,到目前为止,没有模板它是工作好的思想,我可以添加项目,我可以打印它们,但是当我尝试把它放在一个模板,我得到以下错误: use of class模板需要模板参数列表。可能是什么问题?也许我做的完全错了。欢迎任何建议。

so i want to make a code, that creates a binary tree, that holds data, for example ints like 1,6,2,10,8 and on pop i get the biggest number, and after that it gets deleted from the tree, and on push i can insert a new element. And this should be in a template so i can easy change the data type i want to hold in the tree. Now i got the tree so far, without template it is working fine thought, i can add items, and i can print them, but when i try to put it in a template, i get the following error: use of class template requires template argument list . What could be the problem? Maybe i am doing it totally wrong. Any suggestions are welcome.

我得到以下代码:

#include <iostream>


using namespace std;


template<class T>
class BinaryTree
{
struct Node
    {
        T data;
        Node* lChildptr;
        Node* rChildptr;

        Node(T dataNew)
        {
            data = dataNew;
            lChildptr = NULL;
            rChildptr = NULL;
        }
    };
private:
    Node* root; 

        void Insert(T newData, Node* &theRoot)
        {
            if(theRoot == NULL)
            {
                theRoot = new Node(newData);
                return;
            }

            if(newData < theRoot->data)
                Insert(newData, theRoot->lChildptr);
            else
                Insert(newData, theRoot->rChildptr);;
        }

        void PrintTree(Node* theRoot)
        {
            if(theRoot != NULL)
            {
                PrintTree(theRoot->lChildptr);
                cout<< theRoot->data<<" ";;
                PrintTree(theRoot->rChildptr);
            }
        }

    public:
        BinaryTree()
        {
            root = NULL;
        }

        void AddItem(T newData)
        {
            Insert(newData, root);
        }

        void PrintTree()
        {
            PrintTree(root);
        }
    };

    int main()
    {
        BinaryTree<int> *myBT = new BinaryTree();
        myBT->AddItem(1);
        myBT->AddItem(7);
        myBT->AddItem(1);
        myBT->AddItem(10);
        myBT->AddItem(4);
        myBT->PrintTree();
    }


推荐答案

>

In the expression

new BinaryTree()


$ b b

标识符 BinaryTree 是一个模板,而不是类。您可能意味着

the identifier BinaryTree is a template, not a class. You probably meant

new BinaryTree<int>()

这篇关于在模板的二进制树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆