首页 > 解决方案 > 编写一个通用遍历函数,允许灵活处理具有不同参数的多个函数

问题描述

我想使用 std::function 来帮助我运行一个遍历 BST 并调用参数化函数的通用遍历函数。

我的困难是参数化函数的参数不同。

因此,例如,我要概括以下三个函数(它们的参数都不同)。

//populates an array with the values in the BST by traversing the BST
void LinkedBST<T>::populate(T const * const data, size_t & I, Node *x)

{
      data[i++] = x->val;
}

//insert unique values of another BST into "this" BST: traverses the other BST and inserts every value
void LinkedBST<T>::insert(Node *x)
{
      insert(x->val);
}

我不想为上述每个函数编写一个单独的遍历函数,而是希望能够将它们传递给一个通用遍历函数,例如:

void LinkedBST<T>::traverse(Node *x, auto func)
{
     if(x == nullptr)
          return;

     traverse(x->left, func);
     func( <parameters> );
     traverse(x->right, func);
}

有没有办法做到这一点?如果有,你能帮我做吗?

谢谢 :)

标签: c++functiondata-structuresbinary-search-tree

解决方案


一般来说,您需要找到一种方法来标准化所有遍历回调的签名。一种选择是使用 lambda 并利用 lambda 捕获来减少函数的参数数量。

void LinkedBST<T>::populate(T const * const data, size_t & I)
{
    traverse(root, [&](Node * x) {
            data[i++] = x->val;
        });
}

请注意,不能使用相同的遍历函数,compare因为您需要同时遍历两棵树。而且还不清楚insert甚至应该做什么,但从评论中听起来它也需要同时遍历。


推荐阅读