Reputation: 41022
In C, if I have a tree or linked list, I have to declare a function for insertion like
insert(Node ** node)
so I can insert a new root/head.
My question is, how to write it with references in C++?
Upvotes: 0
Views: 148
Reputation: 17546
As templatetypedef said. Or:
ReturnType insert(Node &node)
which is what I would prefer. I like to type .
instead of ->
(saves a char :))
Caller would of course have to ensure that he creates Node
objects with proper scope or creates them using new
.
Node notGood;
Node *goodPtr = new Node();
insert(notGood); //problem
insert(*goodPtr); //ok
Upvotes: 0
Reputation: 373462
You would write the function as
ReturnType insert(Node* &node)
That is, the parameter is a reference to the Node*
variable holding the root of the tree. From there, you would proceed as usual, except that compared with the C version of the function you wouldn't need to dereference node
to reassign the root For example, if you were to write the following in the initial (C) version of the code:
*node = /* ... something ... */
You would just write
node = /* ... something ... */
in the updated version of the code.
Hope this helps!
Upvotes: 1