親クラスの電話を受けました
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;
したがって、通常のオブジェクトソートを使用できます。