gpt4 book ai didi

c++ - 将一个函数分配给另一个

转载 作者:行者123 更新时间:2023-11-27 22:58:17 25 4
gpt4 key购买 nike

我正在尝试实现一个 RedBlack 树,这棵树包含一些 2D 点。我想要 2 棵 RedBlack 树,第一个根据第一个元素(比如 x)对点进行排序,第二个根据第二个元素(比如 y)对点进行排序。我不想为这项任务准备两棵独立的树。所以我决定将一个函数传递给比较点的红黑树的构造函数。例如:

bool xCompare(Point a, Point b) {return a.x < b.x ;}
bool yCompare(Point a, Point b) {return a.y < b.y ;}

所以我可以写:

RedBlackTree A(xCompare); RedBlackTree B(yCompare);

问题是我不知道如何将这个传递的函数保存到构造函数中,以便每次我调用 insert 函数时,插入都基于这个传递的函数。例如,如果我写:

A.insert(make_point(2,3));
A.insert(make_point(7,5));
A.insert(make_point(11,1));

A 中的点应该根据xCompare 进行排序。但是我不知道如何在我的类中保存这个 xCompare 函数(就像一个私有(private)函数)以便 insert 可以访问它。

最佳答案

你可以给你的树一个函数指针数据成员,并在构造函数中设置它:

struct rb_tree
{
rb_tree(bool(*)(Point a, Point b) cmp) : cmp_(cmp) { .... }
....
private:
bool (*cmp_)(Point a, Point b);
};

然后,

rb_tree A(xCompare);
rb_tree(B(yCompare);

您可以通过使用仿函数的模板参数或将数据成员设为 std::function<bool(Point, Point)> 将其泛化为任何类型的兼容可调用对象。 .例如

struct rb_tree
{
rb_tree(std::function<bool(Point, Point)> cmp) : cmp_(cmp) { .... }
....
private:
std::function<bool(Point, Point)> cmp_;
};

与函数指针示例类似的用法,或者

template <typename F>
struct rb_tree
{
rb_tree(F cmp) : cmp_(cmp) { .... }
....
private:
F cmp_;
};

然后

struct cmpA{ bool operator()(Point a, Point b); };
struct cmpB{ bool operator()(Point a, Point b); };

rb_tree<cmpA> A(cmpA_instance);
rb_tree<cmpB> A(cmpB_instance);

但是请注意,在最后一个示例中,树的类型不同。

关于c++ - 将一个函数分配给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com