0

假设我们有类名 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);
}
4

1 回答 1

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并删除它。

于 2013-11-09T11:57:13.613 回答