我有一个标头,它由不同的模板函数组成
#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
。如何使用标题中lessThan
和greaterThan
的模板函数对p2dL
进行排序?即根据x
或y
值对列表进行排序。
编辑:因此,根据安东的评论,我想出了这个:
bool Point2D::operator<(Point2D p2d) {
if (this->x < p2d.x || this->y < p2d.y
|| this->distFrOrigin < p2d.distFrOrigin) {
return true;
}
else {
return false;
}
}
我做对了吗?
首先,只要您强制实施严格的排序,就可以仅使用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 指出的那样,直接使用列表排序:
p2dl.sort(lessThan<Point2D>);
希望有帮助。
您可以直接使用 std::list::sort
方法,而不是 std::sort
:
p2dl.sort(lessThan<Point2D>);
但是您必须根据点类型实现lessThan
和greaterThan
或类似功能。例如:
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);
}