【问题标题】:Sorting List container using template function使用模板函数对列表容器进行排序
【发布时间】:2012-11-05 21:38:12
【问题描述】:

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

#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&lt;Point2D&gt; p2dL。如何使用标题中的模板函数lessThangreaterThanp2dL 进行排序?即根据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;

    }

}

我做对了吗?

【问题讨论】:

  • 你需要为你的类实现
  • 没有“正确”的方式来订购两个 2D 点。您必须决定哪个任意选择适合您的问题。

标签: c++ list function templates sorting


【解决方案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);
}

【讨论】:

    【解决方案2】:

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

    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 &lt;() 以将 *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>);
    

    或者正如胡安指出的,直接使用列表排序:

    p2dl.sort(lessThan<Point2D>);
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      相关资源
      最近更新 更多