通过函数传递自定义比较器 [英] Pass a custom comparator through a function

查看:184
本文介绍了通过函数传递自定义比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有一个函数

MyClass::doStuff(std::vector<MyCustomData*> toSort) { ...

其中我叫

std::sort(toSort.begin(), toSort.end(), MyClass::SortByZ());

myClass :: SortByZ()是一个自定义比较器。
现在这个工作,但我想实现以下:

myClass::SortByZ() is a custom comparator. Now this works but I would like to achieve the following:

我有几个类,每个都应该有自己的比较器函数排序MyCustomData。例如Class1 ...应该有

I have several classes, which should each have its own comparator functor to sort "MyCustomData". So e.g. Class1... should have

class Class1 {
    struct SortData {
        bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
        return lhs->something1 > rhs->something1;
        }
    };
    //...many more functions/vars
}

对于相同的数据类型具有不同的比较函数,例如

while Class2 has a different comparator functor for the same datatype eg

class Class2 {
    struct SortData {
        bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
        return lhs->something2 > rhs->something2;
        }
    };
    //...many more functions/vars
}

希望能够使用

doStuff(myData, Class1::SortData)

doStuff(myData, Class2::SortData)

:doStuff(...)应该使用相应的Sort-Order。

and the function MyClass::doStuff(...) should use the respective Sort-Order.

我没有找到办法做这个,有吗?我想要一个简单的解决方案(不必支持模板或任何东西)。如果我需要,我会愿意使用boost,但是没有boost的解决方案将是首选。

I did not find out a way of doing this, is there one? I would like a simple solution (doesn't have to support templates or anything). I would be willing to use boost if I needed that, but a solution without boost would be preferred.

我希望我能描述我想要实现什么?非常感谢您的帮助!

I hope I was able to describe what I want to achieve? Thanks for any help!

推荐答案

您必须使 doStuff 模板:

template <typename Comparator>
void doStuff(std::vector<MyCustomData*> toSort, Comparator compare) {
   // ...
   std::sort(toSort.begin(), toSort.end(), compare);
   // ...
}

第一个参数通过引用。实际上,它将排序参数的副本,丢弃该副本,并保留调用者的向量不变;虽然也许这是你想要的。

Also, it might want to take the first argument by reference. As it is, it will sort a copy of the argument, discard that copy, and leave the caller's vector untouched; although perhaps that's what you want.

这篇关于通过函数传递自定义比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆