[英]C++ sort vector using non-static member function
I have a class called Sorter
. 我有一堂课叫做Sorter
。 It has two public items. 它有两个公共项目。
int
type variable choice
int
变量choice
compare
with a int
type return value that accepts two objects as parameter. 名为compare
成员函数,带有一个接受两个对象作为参数的int
类型返回值。 I tried creating an instance of Sorter
while passing choice
with a value to the constructor, 我尝试创建Sorter
实例,同时将带有值的choice
传递给构造函数,
Then i wanted to use C++ sort
function to sort a vector
. 然后我想使用C ++ sort
功能对vector
进行排序。 and to pass the member function compare
of the instance i created. 并通过成员函数compare
我创建的实例。
The compare
member function uses the variable choice
to decide the sorting mechanism. compare
成员函数使用变量choice
来确定排序机制。
But i was not able to get the pointer to the member function compare
of an instance of Sorter
. 但是我无法获得指向Sorter
实例的成员函数compare
的指针。
Could someone advice me on this? 有人可以建议我吗?
If you can change the structure of your Sorter
class, you could make it a function object by defining operator ()
like this: 如果可以更改Sorter
类的结构,则可以通过定义operator ()
使其成为一个函数对象,如下所示:
bool Sorter::operator ()(const MyObject &o1, const MyObject &o2) {
// return true if o1 < o2
}
Then you can just pass an instance of your Sorter
class to std::sort
. 然后,您可以将Sorter
类的实例传递给std::sort
。
Unfortunately, the standard library is a bit lacking in combinators for things like this. 不幸的是,标准库在诸如此类的东西中缺少组合器。 However, boost::lambda can do the job: 但是, boost :: lambda可以完成以下工作:
#include <boost/lambda/bind.hpp>
namespace l = boost::lambda;
struct foo {
bool bar(char, char);
};
void test(foo *pFoo) {
char a[2] = {0};
std::sort(a, a+1,
l::bind(&foo::bar, pFoo, l::_1, l::_2));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.