Search code examples
c++binary-search-tree

Finding the average of a variable belonging to an object in a BST?


I am very new to cpp and am currently facing the following problem.

I have csv file filled with Person object class which I need to insert into my BST.

class Person{
        string name;
        string job;
        int age;
}

I have successfully populated my BST with this Person object. I now need to calculate the average age of all the Persons in the BST (there is an appropriate getter method for the age).

I have the following as my inorder traversal (with function pointers)

template <class T>
void Bst<T>::InOrder(Node<T>* root, void(*InOrderPtr)(T &)) const
{
    if (root->left != nullptr)
    {
        InOrder(root->left, *InOrderPtr);
    }

    InOrderPtr(root->GetData());

    if (root->right != nullptr)
    {
        InOrder(root->right, *InOrderPtr);
    }
}
template <class T>
void Bst<T>::InOrderTraversal(void (*InOrderPtr)(T&)) const
{
    InOrder(this->root, *InOrderPtr);
}

However I am stuck in that I do not know how to proceed next to traverse and find the average of all the ages. Can someone direct me how to do so?


Solution

  • Make the second argument to the BST visitor not a function pointer but a templated argument:

    template <typename T, typename Callback>
    void Bst<T>::InOrder(Node<T>* root, Callback&& callback) const {
      // ...
      callback(root->getData());
      // ...
    }
    
    template <typename T, typename Callback>
    void Bst<T>::InOrderTraversal(Callback&& callback) const
    {
        InOrder(this->root, std::move(callback));
    }
    

    That will allow you to not only pass a function pointer if you like, but also pass a lambda function with state:

    int sum = 0;
    int num = 0;
    bst->InOrderTraversal([&](Person const& person) {
      sum += person.age;
      num += 1;
    });
    auto const average = static_cast<float>(sum) / num;