访问函数中的二叉搜索树

时间:2015-06-06 10:04:44

标签: c++ binary-search-tree

请考虑以下代码:

#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.
}

ClassB的运营商已经超载。如果你愿意,可以考虑使用它作为主键。

**编辑 感谢Joachim Pileborg,我开始使用/了解占位符和绑定。

现在我要发布的是我的实际实现,但概念是相同的。单位= ClassB。 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&lt; 1&gt ;,std :: reference_wrapper&gt;))(std :: string,BSTree&amp;)&gt; &gt;(std :: _ Bind(std :: _ Placeholder&lt; 1&gt ;,std :: reference_wrapper&gt;))(std :: string,BSTree&amp;)&gt;)&#39; |

此时有点卡住,我错过了什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您的问题有几种解决方案。最明显的当然是修改getTotal函数和回调函数以接受树作为额外参数。

另一个解决方案可能是根本不使用函数指针,而是使getTotal成为模板函数,并将函数类型作为模板参数传递。然后你可以使用std::bind将一个双参数函数传递给getTotalgetTotal不知道实际的函数类型。

这样的东西
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)));

Reference for std::ref