【问题标题】:Error in deleting treap删除trap时出错
【发布时间】:2013-12-11 19:41:42
【问题描述】:

我的treap 有一个procudere 删除,在p=merge(l, merge(m, rs)); 线上我有错误error: non-const lvalue reference to type 'nodeptr' (aka 'node *') cannot bind to a temporary of type 'nodeptr' 所以这里是删除和合并的实现

nodeptr treap::merge(nodeptr &l, nodeptr &r){
    nodeptr result;
    if (!l){
        result=r;
    }
    else if(!r){
        result=l;
    }
    else if(l->cnt > r->cnt){
        l->right=merge(l->right, r);
        result=l;
    }
    else{
        r->left=merge(l, r->left);
        result=r;
    }
    return result;
}

void treap::deletes(nodeptr &p, int x){
    nodeptr l, r, m, rs;
    split(p, x-1, l, r);
    split(r, x, m, rs);
    if (m){
        if (!m->left){
            m=m->right;
        }
        else{
            m=m->left;
        }
    }
    p=merge(l, merge(m, rs));
}

以及我如何将 treap 实现为数据结构。

typedef struct node *nodeptr;
struct node{
    int x;
    long y;
    node* left ;
    node* right ;
    int cnt;
    node(int key=0, long prior=0):  x(key), y(prior), left(NULL), right(NULL), cnt(0)  {}
};

class treap{
public:
    int cnt( nodeptr &p);
    bool find(nodeptr &p, int x);
    void update_cnt(nodeptr &p);
    void split(nodeptr &p, int x, nodeptr &l, nodeptr &r);
    void insert(nodeptr &p, nodeptr &q);
    nodeptr merge(nodeptr &l, nodeptr &r);
    void deletes(nodeptr &p, int x);
};

你能说我,为什么会出现这个错误?我认为一切都很好。对不起,如果问题是nooby。提前致谢。

【问题讨论】:

  • 嗯,错误很明显:您不能将非常量引用绑定到临时对象。那句话的问题到底出在哪里?
  • treap::merge 函数返回nodeptr 类型的临时对象。此对象无法传递给 merge 函数,因为它需要左值引用 nodeptr&

标签: c++ oop tree treap


【解决方案1】:

您遇到了指针引用的烦恼。当您说p=merge(...) 时,编译器会尝试将merge 返回的临时nodeptr 分配给引用。但随后 temp 超出范围,p 不再持有有效参考。遗憾的是,有时您需要使用指针。

【讨论】:

  • 这里不需要指针。我们可以简单地将返回类型更改为nodeptr&,将result = smth;之类的字符串替换为return smth;,并在treap::merge函数中删除局部变量result
  • 是的,但是指针的嵌套 -> 引用 -> 指针通常在某些时候会变得混乱。最好在有意义的地方使用参考资料。引用在此处保存的唯一内容是有时会额外添加一个星号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多