2013-11-09 192 views
0

假设我们有类名默认值有两个属性x和y。
比较对象的默认操作是使用属性x。运算符重载和类型转换

当我们想使用其他属性y以比较这对象,
1.是否安全,创造新的派生类,可以通过使用属性y,然后浇注指针从默认新课改比较,比较的对象?
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); 
} 

回答

2

更好的方法是在排序时传递函数或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并删除它。

+0

听起来不错,但有一种情况是我不能更改函数sort_element的头。 – unbound

+0

如果你不能那么很遗憾你没有选择,你的代码是唯一的选择,那么你应该停止担心效率。 – deepmax