首页 > 解决方案 > 如何传递回调函数将项目推送到向量中

问题描述

所以在我的数据结构类中,我正在编写一个中序遍历函数来遍历 BST 中的节点并将项目推送到向量中。然而,这是我第一次处理回调函数和 lambda。以下是我尝试过的,但出现类型转换错误。任何见解将不胜感激。

template<class ItemType> // Recursion launcher
void BinarySearchTree<ItemType>::inorderTraverse(void visit(ItemType& item)) const {
    if(rootPtr == nullptr) return;
    inorder(rootPtr, visit);
}

template<class ItemType> // I am not allowed to change this function signature
void BinarySearchTree<ItemType>::inorder(BinaryNode<ItemType>* node, void visit(ItemType& item)) const
{ 
    if(node->left) inorder(node->left, visit);
    ItemType item = node->getItem();
    visit(item);
    if(node->right) inorder(node->right, visit);
}

template<class ItemType>
void BinarySearchTree<ItemType>::function() {
    vector<ItemType> temp;
    // The problem is the function below
    auto function = [&temp](auto item){temp.emplace_back(item);}
    inorderTraverse(function);
}

标签: c++lambdacallback

解决方案


推荐阅读