0

2 つの属性 x と y を持つクラス名 Default があるとします。
オブジェクトを比較するデフォルトの操作は、属性 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);
}
4

1 に答える 1

2

それらをソートするときに、ファンクターまたはラムダを比較関数として渡す方がよいでしょう。並べ替え関数は次の関数を受け入れる必要があります。

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());

2 番目のクラスを忘れてCompare1削除します。

于 2013-11-09T11:57:13.613 に答える