假设我们有类名Default,它有两个属性x和y 比较对象的默认操作是使用属性x。
当我们想要使用其他属性y来比较这个对象时,
的 1。创建可以通过使用属性y进行比较然后将指针从Default转换为该新类并比较对象的新派生类是否安全?
2.在不降低操作性能的情况下,有什么方法可以做到这一点?
要求是我们不能改变排序算法的签名来将函数指针传递给差分比较器。
顺便说一下,这种方法不需要转换或复制数据的费用。
class Default {public:int x; int y;};
class Compare1 : public Default {};
bool operator < (const Default &left,const Default &right)
{
return left.x < right.x;
}
bool operator < (const Compare1 &left,const Compare1 &right)
{
return left.y < right.y;
}
template<typename T>
int *sort_element(const T *data, int size)
{
int *permute;
//... do some sorting by using < comparator ...
return permute;
}
int main(){
Default *obj;
int obj_size;
//… initialize obj and obj size..
// sorting object with default order.
int *output_default = sort_element(obj, obj_size)
// sorting with customize comparator.
Compare1 *custom1 = static_cast<Compare1*>(obj);
int *output_custom1 = sort_element(custom1, obj_size);
}
答案 0 :(得分:2)
最好是在对它们进行排序时将functor或lambda作为比较函数传递。您的排序功能必须接受一个功能:
template<typename T, typename F>
int *sort_element(const T *data, int size, F comp)
{
....
if (comp(a, b))
....
...
}
然后
// Sort by x
sort_element(..., [](const Default &a, const Default &b) {
return a.x < b.x;
});
// Sort by y
sort_element(..., [](const Default &a, const Default &b) {
return a.y < b.y;
});
如果您还没有C ++ 11,则可以使用函数对象(仿函数):
struct fx
{
bool operator()(const Default &a, const Default &b) const
{
return a.x < b.x;
}
};
struct fy
{
bool operator()(const Default &a, const Default &b) const
{
return a.y < b.y;
}
};
// Sort by x
sort_element(..., fx());
// Sort by x
sort_element(..., fy());
忘记你的第二堂课Compare1
并删除它。