Click here to Skip to main content
15,888,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I've been given the following instruction:

Add a new method to the library that applies a function to every value in the tree. (This is an iterator method for trees.)

C
int bst_char_iterate(bst_char *t, char (*fun)(char item))


NB: The BST property will only be preserved by this method if the function passed to it is monotonic. A function f is monotonic whenever
x <= y (arrow) f(x) <= f(y).


"Bst_char *t" equating to a pointer to the tree, "*fun" equating to a pointer to a function call and "item" being the value of which the function is called upon.

I've managed to come up with this:

C
int bst_char_iterate(bst_char *t, char (*fun)(char item)) {
    assert(t!=NULL);
    struct node * p = t->root;
    if (p!=NULL) {
       p->item = fun(p->item);
       p->left->item = bst_char_iterate(t,fun(p->left));
       p->right->item = bst_char_iterate(t,fun(p->right));
    } else {
       return 0;
    }
}


This cannot compile, with quite a few errors (such as "from pointer without a cast").

Please help!

Edit: I have managed to get it to compile with this code:

int bst_iterate(struct node *p, char (*fun)(char item)) {
    if (p!=NULL) {
       p->item = fun(p->item);
       bst_iterate(p->left,fun);
       bst_iterate(p->right,fun);
    } else {
       return 0;
    }
}

int bst_char_iterate(bst_char *t, char (*fun)(char item)) {
    assert(t!=NULL);
    bst_iterate(t->root,(fun));
}


But I've no idea how to implement it in the test program.

I've tried:

bst_char_iterate(t, fun);
bst_char_iterate(t, *fun);
bst_char_iterate(t->root, fun);
bst_char_iterate(t, fun(c));
Posted
Updated 6-Jan-14 1:17am
v2
Comments
Richard MacCutchan 6-Jan-14 5:00am    
quite a few errors (such as "from pointer without a cast").
Is it really that difficult to copy and paste the exact error message(s) and also indicate which line they refer to?

Quote:
But I've no idea how to implement it in the test program.

Keeping it simple:
C
// the dumbest monotonic function...
char  my_fun(char c)
{
  return c;
}


int main()
{
  bst_char * ptree;
  // ...
  // ... create the tree, make ptree pointing to it
  // ...
  bst_char_iterate(ptree, my_fun);
  // ...
  // ... free the tree
  // ...
  return 0;
}
 
Share this answer
 
v2
C++
bst_char_iterate(t, fun);         // what type is t?
bst_char_iterate(t, *fun);        // *fun is incorrect, use fun
bst_char_iterate(t->root, fun);   // what type is root?
bst_char_iterate(t, fun(c));      // fun(c) is wrong, use fun

And in all the above cases what is fun and where is it defined?

As I said in my first comment, you need to show the exact error message the compiler produces.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900