mercredi 1 juin 2022

What exactly is std::function

I've recently come across some code for the inorder traversal of a binary search tree which is as follows:

void binary_search_tree::inorder_traversal(bst_node *node, std::function<void(int)> callback) {

    if (node == nullptr) {
        return;
    }

    inorder_traversal(node->left, callback);
    callback(node->value);
    inorder_traversal(node->right, callback);
}

std::vector<int> binary_search_tree::get_elements_inorder() {
    std::vector<int> elements;

    inorder_traversal(root, [&](int node_value) {
        elements.push_back(node_value);
    });

    return elements;
}

From my understanding, the first function recursively traverses the BST inorder, visiting the left, then the node, then the right. The second function then calls this function to add each element to the vector as each node is hit.

My confusion comes from how each value of the node is obtained. Does callback(node->value) store each node value somewhere to be used later? I'm not exactly sure about how this works.

Any help would be much appreciated :) Thank you!

Aucun commentaire:

Enregistrer un commentaire