C ++如何对数组变量进行排序

时间:2012-11-03 09:16:42

标签: c++

我有一个父类调用

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[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未在此范围内声明。

我尝试过的另一件事是: 使用向量

排序

在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;

所以我可以使用普通的对象排序。

2 个答案:

答案 0 :(得分:3)

在你的代码中你是如何期望编译器知道你想要按区域排序,魔术?我建议读一本关于标准C ++库(又名STL)的书,它将解释如何进行自定义排序。在你的代码中你有一个指针的数组,所以你应该编写一个可以命令指针的仿函数。你的std :: sort参数也是错误的。您的数组从shaped开始,到shaped + 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所说。

答案 1 :(得分: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);