i am creating a binary search tree template class, and want to use function pointers for the inorder traversal function, i am okay with function pointers but for some reason am lost on how to use the inorder once the code is in place. not much other stuff online has helped me so any feed back would be great.
class Bst
{
struct Node
{
T data;
Node * left;
Node * right;
Node(T key) :data(key), left(nullptr), right(nullptr) {}
};
typedef void(*inorderPtr)(T &);
typedef void(*preorderPtr)(T &);
typedef void(*postorderPtr)(T &);
Node * root;
T & GetItem() const;
void deleteNode(Node*);
void printNode(Node*);
void inorder(Node * root, void (*inorderPtr)(T &)) const;
void preorder(Node * root) const;
void postorder(Node * root) const;
public:
Bst();
~Bst();
Bst(const Bst<T> & source);
const Bst<T> & operator = (const Node &);
void insert(const T);
void print();
void inorder(void(*inorderPtr)(T &)) const;
void printPreorder() const;
void printPostorder() const;
};
some code is as follows for basic bst
template<class T>
inline T & Bst<T>::GetItem() const
{
return data;
}
template<class T>
inline void Bst<T>::inorder(Node * root, void(*inorderPtr)(T &)) const
{
if (root->left != nullptr)
{
inorder(root->left, inorderPtr);
}
inorderPtr(root->GetItem());
if (root->right != nullptr)
{
inorder(root->right, inorderPtr);
}
}
template<class T>
inline void Bst<T>::inorder(void(*inorderPtr)(T &)) const
{
inorder(this->root, inorderPtr);
}
int main()
{
Bst<int> tree;
for (int i = 0; i < 100; i++)
{
tree.insert(i);
}
tree.inorder();
}
the main is basic test but having trouble with inorder(); not enough arguments
Lets say you want to print the value of each node in the tree:
void value_printer(int& value)
{
std::cout << "Value is " << value << '\n';
}
int main()
{
Bst<int> tree;
// Insert nodes...
tree.inorder(&value_printer);
}
You pass a pointer to the value_printer
function in the inorder
call. That function will then be called for each node in the traversal.
The function you pass a pointer to can do other things, of course. And as it is currently declared, you can even modify the values of the tree.
Learn more about std::function
and lambda expressions. See also this answer.