【发布时间】: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&。