在函数中访问二叉搜索树
Accessing Binary Search Tree in a Function
考虑以下代码:
#include "ClassB.h"
ClassA
{
private:
Vector<std::string> idVec;
public:
int getTotal(ClassB& (*func) (std::string));
}
int ClassA::getTotal(ClassB& (*func) (std::string))
{
int total = 0;
for (int i:0; i < idVec.Size(); i++)
{
total += (*func) (idVec[i]).GetInt();
}
return total;
}
ClassB
{
private:
string id;
int i;
public:
std::string getId();
int getInt();
}
ClassB& accessTree(stD::string id);
main()
{
BSTree<ClassB> //Binary Search Tree
ClassA a;
//Assume id's get set.
a.getTotal(accessTree);
}
ClassB& accessTree(stD::string id)
{
//This is part I'm not 100% on.
}
类b的操作符已被重载。如果你愿意,可以把id当作主键。
* *编辑所以感谢Joachim Pileborg,我已经开始使用/学习占位符和绑定。
现在我要发布的是我的实际实现,但概念是相同的。单位= b类。R(即注册)= ClassA.
调用函数template<typename Ft>
unsigned Registration::GetCredits(Ft func)
{
unsigned sum = 0;
for(unsigned i = 0; i < GetSize(); i++)
sum += results[i].GetCredits(func(results[i].GetUnit()));
return sum;
}
Unit& accessTree(std::string id, BSTree<Unit>& tree)
{
Unit tempU;
tempU.SetId(id);
return tree.search(tempU);
}
主要R.GetCredits(std::bind(accessTree, _1, std::ref(uTree)));
未定义引用' unsigned int Registration::GetCredits(std::_Placeholder<1>, std::reference_wrapper>))(std::string, bstree<)>>(std::_Bind(std::_Placeholder<1>, std::reference_wrapper>))(std:: _Bind(std:: string, bstree<)>)'|
在这一点上有点卡住,我错过了什么?
您的问题有几个解决方案。最明显的方法当然是修改getTotal
函数和回调函数,以接受树作为额外的参数。
另一个解决方案可能是根本不使用函数指针,而是使getTotal
成为一个模板函数,并将函数类型作为模板参数传递。然后,您可以使用std::bind
将两个参数的函数传递给getTotal
,而getTotal
不会真正知道实际的函数类型。
template<typename Ft>
int ClassA::getTotal(Ft func)
{
...
func(idVec[i]);
...
}
像
一样使用ClassB& accessTree(const std::string& id, BSTree<ClassB>& tree);
...
using namespace std::placeholders; // For `_1` etc.
BSTree<ClassB> tree;
a.getTotal(std::bind(accessTree, _1, std::ref(tree)));
(参考std::ref
)
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 访问冲突二叉搜索树模板
- 二叉搜索树 - 访问冲突
- 删除二叉搜索树中的节点中的 Visual Studio 中的访问冲突异常
- 添加节点时C++二叉搜索树状态访问冲突错误
- 访问二叉搜索树中的违规读取位置0x00000000
- 递归函数插入二叉搜索树无法按根访问节点
- 在函数中访问二叉搜索树