我想在类中使用函数nth_element
和我自己的排序函数(应该可以访问对象的数据)。目前,我正在执行以下操作:
class Foo
{
public:
glm::vec3 *points;
int nmbPoints;
bool idxPointCompareX(int a, int b);
void bar();
}
bool Foo::idxPointCompareX(int a, int b)
{return points[a].x < points[b].x;)
void Foo::bar()
{
stl::vector<int> idxPointList;
for(int i = 0; i < nmbPoints; i++) idxPointList.push_back(i);
stl::nth_element(idxPointList.first(),idxPointList.first()+nmbPoints/2,idxPointList.end(), idxPointCompareX);
}
当然,这不起作用,并且我得到了错误:“必须调用对非静态成员函数的引用”。之后,我在这里查看了Reference to non-static member function must be called,How to initialize
std::function
with a member-function?和其他一些问题。我知道为什么这行不通,但是我不确定如何解决。有人可以帮我,告诉我如何解决这个问题吗?
最佳答案
要获取成员函数的地址,您需要使用正确的语法,即&Foo::idxPointCompareX
不仅是idxPointCompareX
但是您还需要一个Foo
对象来调用该函数,因此您需要将其绑定(bind)到该对象。想必您是想在this
上调用它,以便可以使用std::bind
:
using namespace std::placeholders;
stl::nth_element(begin, begin+n, end,
std::bind(&Foo::idxPointCompareX, this, _1, _2));
或更简单的是,使用lambda函数:stl::nth_element(begin, begin+n, end,
[this](int a, int b) { return idxPointCompareX(a, b);}
);
这将创建一个lambda函数,该函数捕获this
并将其参数传递给捕获的this
指针上的idxPointCompareX函数。