C++使用非静态成员函数对向量进行排序
我有一个名为 Sorter
的类。它有两个公共项目。
int
类型变量choice
- 调用
compare
成员函数,其int
类型返回值接受两个对象作为参数。
我尝试创建 Sorter
的实例,同时将带有值的 choice
传递给构造函数,
然后我想使用 C++ sort
函数对 sort
进行排序代码>矢量。并传递我创建的实例的成员函数 compare
。
compare
成员函数使用变量choice
来决定排序机制。
但我无法获取指向 Sorter
实例的成员函数 compare
的指针。
有人可以就此给我建议吗?
I have a class called Sorter
. It has two public items.
int
type variablechoice
- member function called
compare
with aint
type return value that accepts two objects as parameter.
I tried creating an instance of Sorter
while passing choice
with a value to the constructor,
Then i wanted to use C++ sort
function to sort a vector
. and to pass the member function compare
of the instance i created.
The compare
member function uses the variable choice
to decide the sorting mechanism.
But i was not able to get the pointer to the member function compare
of an instance of Sorter
.
Could someone advice me on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以更改
Sorter
类的结构,则可以通过定义operator ()
使其成为函数对象,如下所示:然后您只需传递
Sorter 类的一个实例即可code>Sorter
类到std::sort
。If you can change the structure of your
Sorter
class, you could make it a function object by definingoperator ()
like this:Then you can just pass an instance of your
Sorter
class tostd::sort
.不幸的是,标准库有点缺乏这样的组合器。但是, boost::lambda 可以完成这项工作:
Unfortunately, the standard library is a bit lacking in combinators for things like this. However, boost::lambda can do the job: