“错误:无法将 'int*' 转换为 'int**'”

某物

我尝试实现一个模板 avl 树,而 Node 包含一个指向对象的指针:

template <class T>
class Node {
public:
    Node* left;
    T* data;
    Node* right;
    int height;
};
    
template <class T>
class AVLTree{
public:
    Node<T*>* root;
  
Node<T*>* insert(Node<T*>* p, T* key){
    Node<T*>* t;
    if (p == NULL){
        t = new Node<T*>;
        t->data = key;
        t->left = NULL;
        t->right = NULL;
        t->height = 1;  
        return t;
    }
 
    if (*(key) < *(p->data)){
        p->left = insert(p->left, key);
    } else if (*(key) > *(p->data)){
        p->right = insert(p->right, key);
    }
 


    return p;
}
int main() {
    
    AVLTree<int*>* tree1 = new AVLTree<int*>();

    int a=5;
    int* ap=&a;

   
tree1->root = tree1->insert(tree1->root,ap);  

通过执行这个我得到了一个错误,我希望有足够的关于这个问题的细节。

在此处输入图像描述

请帮忙 。谢谢 !

泰德·林格莫

T = int*并且您说您想要 a T*(即 an int**),T* key因此当您尝试提供 an 时int*,它会失败。

我建议将其更改Node为包含 aT而不是 a T*

template <class T>
class Node {
   public:
    Node* left;
    T data;       // not T*
    Node* right;
    int height;
};
template <class T>
class AVLTree {
public:
    Node<T>* root;

    Node<T>* insert(Node<T>* p, T* key) {
        Node<T>* t;
        if (p == nullptr) {
            t = new Node<T>;
            t->data = *key;
            t->left = nullptr;
            t->right = nullptr;
            t->height = 1;
            return t;
        }

        if (*key < p->data) {
            p->left = insert(p->left, key);
        } else if (*key > p->data) {
            p->right = insert(p->right, key);
        }

        return p;
    }
};

然后实例化一个AVLTree<int>而不是一个AVLTree<int*>


这是一个建议,可以存储指针并使用std::less和比较它们std::greater请注意,如果您存储指针,它将是您比较的实际指针值,而不是指针指向的值。

#include <functional>

template <class T>
class Node {
   public:
    Node* left;
    T data;
    Node* right;
    int height;
};

template <class T>
class AVLTree {
public:
    Node<T>* root;

    Node<T>* insert(Node<T>* p, const T& key) { // key is an int*& in this example
        Node<T>* t;
        if (p == nullptr) {
            t = new Node<T>;
            t->data = key;
            t->left = nullptr;
            t->right = nullptr;
            t->height = 1;
            return t;
        }

        if (std::less<T>{}(key, p->data)) {           // less
            p->left = insert(p->left, key);
        } else if (std::greater<T>{}(key, p->data)) { // greater
            p->right = insert(p->right, key);          
        }

        return p;
    }
};

int main() {
    AVLTree<int*> tree1;

    int a = 5;
    int* ap = &a;

    tree1.root = tree1.insert(tree1.root, ap);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章