C ++将指针数组排序到对象

时间:2012-11-04 07:04:05

标签: c++ class sorting shapes

  

可能重复:
  C++ how to sort an array variable

我有一个父类调用

Shape

Shape有2个孩子的电话

Square and Rectangle

Shape类有一个变量调用区域,它是int类型

所以我创建了一个Square,Rectangle这样的对象

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, shaped + 3, sort_by_area());


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

}

然后在例如Square.cpp

我做了这个

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

以上代码有效。并且可以按区域排序,但我的问题是,如果我不使用struct,我仍可以排序,因为如果我不使用struct,则会说sort_by_area未在范围内声明。

我必须真正使用struct,所以我的main.cpp可以访问位于子类的.cpp

的排序代码。

由于

1 个答案:

答案 0 :(得分:5)

这非常有效:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Shape{

private:
    int x;
public:
    void setArea(int x){
        this->x =  x;
    }
    int getArea(){
        return this->x;
    }
};

class Rectangle: public Shape{
public:
};

class Square: public Shape{
public:
};

bool sort_by_area (Shape* x,Shape* y) { return (x->getArea() < y->getArea()); }
int main()
{
    Shape *shaped[100];

    //then i did some adding of object..
    int areaValue,shapeCounter = 0;
    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, shaped + 3, sort_by_area);


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