在函数中访问二叉搜索树

Accessing Binary Search Tree in a Function

本文关键字:搜索树 访问 函数      更新时间:2023-10-16

考虑以下代码:

#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)