c++ - Passing "constant pointers" to functions -
i've written program performs various operations on binary tree. @ beginning set null root pointer, call couple of insert()
functions add new nodes tree.
finally, call search()
function finds requested structure node , returns it.
insert()
function takes 2 parameters - reference root pointer, , constant int key, converted node structure , added tree
search()
function takes "constant root pointer" - not reference, because want operate on local pointer directly, , don't want changed. other argument takes int key.
this whole program:
#include <iostream> struct node { node *p; // parent node *left, *right; int key; }; void insert(node *&root, const int key) { node newelement = {}; newelement.key = key; node *y = null; while(root) { if(key == root->key) exit(exit_failure); y = root; root = (key < root->key) ? root->left : root->right; } newelement.p = y; if(!y) root = &newelement; else if(key < y->key) y->left = &newelement; else y->right = &newelement; } node* search(const node *root, const int key) { while( (root) && (root->key != key) ) root = (key < root->key) ? root->left : root->right; return root; } int main() { using namespace std; node *root = null; insert(root, 5); insert(root, 2); cout << search(root, 5)->key << endl; return 0; }
my question - why doesn't search function work? displays error - return value type not match function type. return poiner, says in declaration!
also, "const"
keyword here o.k.?
root
const node*
, , return value node*
. should changed const node*
.
const node* search(const node *root, const int key);
if need search
function give non-const node
, needs take non-const node
parameter. can provide overload allow both possibilities
node* search(node *root, const int key);
Comments
Post a Comment