c++ - 编写一个通用遍历函数,允许灵活处理具有不同参数的多个函数
问题描述
我想使用 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);
}
有没有办法做到这一点?如果有,你能帮我做吗?
谢谢 :)
解决方案
一般来说,您需要找到一种方法来标准化所有遍历回调的签名。一种选择是使用 lambda 并利用 lambda 捕获来减少函数的参数数量。
void LinkedBST<T>::populate(T const * const data, size_t & I)
{
traverse(root, [&](Node * x) {
data[i++] = x->val;
});
}
请注意,不能使用相同的遍历函数,compare
因为您需要同时遍历两棵树。而且还不清楚insert
甚至应该做什么,但从评论中听起来它也需要同时遍历。
推荐阅读
- sdk - UserStory ScheduleState 在 Grid 中显示
- excel - 将变量添加到 .Attachments.Add
- xamarin - 最近的媒体 instagram GET 请求返回状态 200 但为空数据
- python - 如何在 Python 中读取带有数字的文件中的特定行?
- mysql - 如何在 MariaDB (MySQL) 中合并两个数据库
- angular - Angular CLI 测试和枚举
- php - PHP 获取元标记功能不适用于非 http
- mutex - 在使用 Vivado HLS 时,如何用适当的功能替换互斥锁?
- postgresql - Clojure jdbc 创建复合主键
- python - Gunicorn 使用 Vue 参考大大减慢了 Flask 的执行速度