我试图调用我的heapify函数,它应该创建一个二叉树,并以一种方式对它进行排序,这取决于我的布尔函数参数。
我的问题:我不确定在调用我的heapify函数时如何在main中传递函数指针。
我尝试传递值和我的代码的尝试在下面(我在尝试调用函数时遇到错误:表达式必须是左值或函数指示符)
struct S {
double x;
int n;
char c;
};
void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b));
int main() {
S test[9] = { {1.1,1,'A'},{1.3,2,'B'},{1.8,3,'C'},{1.7,4,'D'},{5.1,5,'E'},{4.3,6,'F'},{3.8,7,'G'},{4.7,8,'H'},{2.7,9,'I'} };
heapify(x, 9,&shouldBeBefore(test[0], test[1]));
return 0;
}
bool shouldBeBefore(const S & a, const S & b) {
if (a.x < b.x) {
return true;
}
else {
return false;
}
}
将你的shouldBeBefore
声明(或整个定义)移到main
上方,你调用heapify
。但是当你调用heapify
时,你只需传入函数名称。 heapify
将使用它自己的参数调用你的shouldBeBefore
函数。
void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b));
bool shouldBeBefore(const S & a, const S & b);
int main()
{
S test[9] = { {1.1,1,'A'},{1.3,2,'B'},{1.8,3,'C'},{1.7,4,'D'},{5.1,5,'E'},
{4.3,6,'F'},{3.8,7,'G'},{4.7,8,'H'},{2.7,9,'I'} };
unsigned int length = sizeof(test)/sizeof(test[0]); // 9
heapify(S, length, shouldBeBefore);
return 0;
}
bool shouldBeBefore(const S & a, const S & b)
{
return (a.x < b.x);
}
在heapify
的实现中,您可以像调用任何其他函数一样调用shouldBeBefore
:
void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b))
{
...
if (shouldBeBefore(S[i+1], S[i]) {
...
}
...
}
添加到上一个答案,我只想清除对函数指针和函数的假设混淆。
void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b));
int main() {
[...]
heapify(x, 9, shouldBeBefore(test[0], test[1]));
[...]
}
bool shouldBeBefore(const S & a, const S & b) {
return a.x < b.x;
}
shouldBeBefore
命名函数以及函数参数。这增加了一些困惑。 heapify
实际上被允许带有签名bool(const S&, const S&)
的任何功能,名称应该这样建议。
对于函数指针,添加类型定义总是很方便
using Comparator = bool(*)(const S&, const S&);
// typedef bool(*Comparator)(const S&, const S&); // or by typedef
然后代码看起来像
void heapify(S bt[], unsigned els, Comparator comparator);
int main() {
[...]
heapify(x, 9, shouldBeBefore(test[0], test[1]));
[...]
}
bool shouldBeBefore(const S & a, const S & b) {
return a.x < b.x;
}
你可以像任何其他函数一样调用比较器。
定义函数指针有点冗长。你也可以使用std :: function,它会提供更轻松的语法
using Comparator = std::function<bool(const S&, const S&>>;
优点是你可以用任何可调用的方法调用heapify。