2013-11-09 103 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