1

さまざまなテンプレート関数で構成されるヘッダーがあります

#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> p2dLp2dLテンプレート関数lessThangreaterThanヘッダーを使用して並べ替えるにはどうすればよいですか?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;

    }

}

私はそれを正しくしましたか?

4

2 に答える 2

2

まず、厳密な順序付けを適用する限り、3 つの主要なテンプレートはすべて を使用して公開できます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>);

それが役立つことを願っています。

于 2012-11-17T08:31:30.690 に答える
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);
}
于 2012-11-17T08:11:46.853 に答える