使用模板功能对List容器进行排序

时间:2012-11-17 08:06:37

标签: c++ list function templates sorting

我有一个标题,它由不同的模板函数组成

#include <cmath>

template<class T>
bool lessThan(T x, T y) {

    return (x < y);

}

template<class T>
bool greaterThan(T x, T y) {

    return (x > y);

}

一个班级

class Point2D {
public:
    Point2D(int x, int y);
protected:
    int x;
    int y;
    double distFrOrigin;

在我的驱动程序类中,我有一个Point2D的STL列表:list<Point2D> p2dL。如何使用标题中的模板函数p2dLlessThangreaterThan进行排序?即根据xy值对列表进行排序。

编辑:所以,基于Anton的评论,我想出了这个:

bool Point2D::operator<(Point2D p2d) {

    if (this->x < p2d.x || this->y < p2d.y
            || this->distFrOrigin < p2d.distFrOrigin) {

        return true;

    }

    else {

        return false;

    }

}

我做得对吗?

2 个答案:

答案 0 :(得分:2)

首先,只要您强制执行严格的排序,就可以使用 operator <()公开所有三个主要模板:

template<class T>
bool lessThan(const T& x, const T& y) 
{
    return (x < y);
}

template<class T>
bool greaterThan(const T& x, const T& y) 
{
   return (y < x);
}

template<class T>
bool equals(const T& x, const T& y) 
{
   return !(x < y) || (y < x));
}

接下来,您的班级必须实施operator <()以将*this与参数进行比较。下面显示了一个示例:

class Point2D {
public:
    Point2D(int x, int y);

    // sample that orders based on X primary, and Y if X's are equal.
    bool operator <(const Point2D& other) const
    {
        return (x < other.x || (x == other.x && y < other.y));
    }

protected:
    int x;
    int y;
    double distFrOrigin;
};

最后。像这样排序你的列表:

// sort ascending
std::sort(p2dl.begin(), p2dl.end(), lessThan<Point2D>);

// sort descending
std::sort(p2dl.begin(), p2dl.end(), greaterThan<Point2D>);

或者如Juan指出的那样,直接使用list-sort:

p2dl.sort(lessThan<Point2D>);

希望有所帮助。

答案 1 :(得分:1)

您可以直接使用std::list::sort方法,而不是std::sort

p2dl.sort(lessThan<Point2D>);

但是你必须在Point类型方面实现lessThangreaterThan或类似的功能。例如:

template<class T>
bool greaterThan(const T& p1, const T& p2) {

    return (p1.x > p2.y);

}

请注意,上面的比较函数只是一个示例,您必须决定如何使用2D点来实现小于和大于。

为了完整起见,这是使用std::tie进行词典比较:

template<class T>
bool greaterThan(const T& p1, const T& p2) 
{
    return std::tie(p1.x, p1.y) > std::tie(p2.x, p2.y);
}