-4

親クラスの電話を受けました

Shape

シェイプは2つの子コールを取得しました

Square and Rectangle

Shapeクラスは、int型の可変呼び出し領域を取得しました

だから私はこのような正方形、長方形のいくつかのオブジェクトを作成しました

int main()
{
    Shape *shaped[100];

    //then i did some adding of object..
    int areaValue;
    areaValue=1;

    shaped[0] = new Rectangle();
    shaped[0]->setArea(areaValue);

    areaValue=7;
    shaped[1] = new Square();
    shaped[1]->setArea(areaValue);

    areaValue=5;
    shaped[2] = new Square();
    shaped[2]->setArea(areaValue);

    shapeCounter = 3;

    sort(shaped[0],shaped[2]);

    for (int i=0;i<shapeCounter;i++)
    {
        cout << shaped[i].getArea() << endl;
    }

}

昇順で並べ替えようとしましたが、うまくいきません。位置の変更はなく、領域は同じシーケンスのままです。

すべての助けをありがとう!

アップデート:

Shape.cppで次の変更を行いました

 bool Shape::orderByArea(const Shape* lhs, const shape* rhs)
    {
      return lhs->area() < rhs->area();
    }

それからmain.cppで私はこれをしました

std::sort(shaped, shaped + 3, orderByArea);

ただし、エラーが発生しました。orderByAreaはこのスコープで宣言されていません。

私が試したもう1つのことは 、ベクトルを使用して並べ替えることです。

Shape.hで

public:

bool operator<const Shape& x) const
{
return area < x.area;
}

main.cppで

vector<ShapeTwoD*> sortVector;
sortVector.clear();
sortVector.assign(shaped,shaped + shapeCounter);

sort(sortVector.begin(),sortVector.end());

for(int i=0;i<shapeCounter;i++)
{
cout << sortVector[i].toDisplay() << endl;
}

しかし、何もソートされていないようです。位置が同じでプリントアウトしてみます。

更新:修正されました。並べ替えが機能しています。専門家に感謝します!

別の質問があります

形*形[100];

の値をコピーするにはどうすればよいですか

Shape *shaped[100];

の中へ

vector<Shape> myVector;

それ以外の

vector<Shape*> myVector;

したがって、通常のオブジェクトソートを使用できます。

4

2 に答える 2

4

あなたのコードでは、あなたがエリア、魔法でソートしたいということをコンパイラがどのように知っていると思いましたか?標準C++ライブラリ(別名STL)の本を読むことをお勧めします。これは、カスタムソートの方法を説明しています。コードにはポインターの配列があるので、ポインターを並べ替えることができるファンクターを作成する必要があります。また、std::sortへのパラメータが間違っています。配列はで始まりshaped、で終わりshaped + 3ます(配列には3つの要素があるため)。

struct sort_by_area
{
    static bool operator()(Shape* x, Shape* y)
    {
        return x->getArea() < y->getArea();
    }
};

sort(shaped, shaped + 3, sort_by_area());

テストされていないコード、間違いをお詫びします。

または、juanchopanzaが言うように関数ポインタを使用することもできます。

于 2012-11-03T09:20:49.333 に答える
1

shapesでいっぱいの配列がありShape*、それにShapeメソッドがあると仮定するとint getArea() const;、比較未満のロジックを定義してから、それstd::sortを使用するように指示する必要があります。この種の小なり関数を定義することにより、前者を行うことができます。

inline bool orderByArea(const Shape* lhs, const shape* rhs)
{
  return lhs->getArea() < rhs->getArea();
}

次に、を呼び出しstd::sort、関数へのポインタを渡します。

#include <algorithm>

Shape* shapes[3] = ....; // array of three pointers to Shape
std::sort(shapes, shapes + 3, orderByArea);
于 2012-11-03T09:22:12.450 に答える