如何在数组之外对自定义类对象进行排序

How to sort custom class objects iside of an array

本文关键字:对象 排序 自定义 数组      更新时间:2023-10-16

我想知道如何对包含自定义类对象的数组进行排序。我试图应用不同的排序算法,但在交换中出现问题。

下面是我的代码:

class RaceCar
{
private:
    char* _brand;
    char* _model;
    double _price;
    int _horse_power;
public:
    //Other code
    RaceCar(const RaceCar& rc):_price(rc._price), _horse_power(rc._horse_power)
    {
         _brand = new char[strlen(rc._brand)+1];
         strcpy(_brand, rc._brand);
         _model = new char[strlen(rc._model)+1];
         strcpy(_model,rc._model);
    }
    RaceCar& operator=(const RaceCar& rc)
    {
        if(this != &rc)
        {
            delete _brand;
            delete _model;
            _brand = new char[strlen(rc._brand)+1];
            strcpy(_brand, rc._brand);
            _model = new char[strlen(rc._model)+1];
            strcpy(_model, rc._model);
            _price = rc._price;
            _horse_power = rc._horse_power;
        }
        return *this;
    }
    bool operator<(const RaceCar& rc)
    {
        return (this->_price/this->_horse_power) > (rc._price/rc._horse_power);
    }
    //Other code
};

这个类包含一个RaceCars数组。我试图实现SortCars()方法,命令赛车数组内的RaceCar对象:

class RaceCarGarage
{
private:
    RaceCar* _cars;
    int _max_cars;
    int _curr_occupied;
public:
    RaceCarGarage():_cars(NULL), _max_cars(0),_curr_occupied(0){}
    RaceCarGarage(const RaceCar& car, int max_cars)
    :_max_cars(max_cars), _curr_occupied(0)
    {
        _cars = new RaceCar[_max_cars];
    }
    ~RaceCarGarage()
    {
        delete _cars;
    }
    void AddCar(const RaceCar& car)
    {
        if(_curr_occupied < _max_cars)
        {
            _cars[_curr_occupied] = car;
            _curr_occupied += 1;
        }
    }
    void DisplayCars()
    {
        if(_curr_occupied > 0)
        {
            for(int i=0 ; i<_curr_occupied ; i++)
            {
                cout<<(i+1)<<". ";
                (_cars+i)->Display();
            }
        }
    }
    void SortCars()
    {
        if(_curr_occupied > 1)
        {
            for(int i=0 ; i<_curr_occupied ; i++)
            {
                for(int j = i+1 ; j<_curr_occupied ; j++)
                {
                    if(_cars[j]<_cars[i])
                    {
                        RaceCar buffer = _cars[i];
                     _cars[i] = _cars[j];
                     _cars[j] = buffer;
                    }
                }
            }
        }
    }
};

交换的问题是您使用传统的方式:

temp = a        // operator= 
a = b           // operator=
b = temp;       // operator= 

但是,如果你写:

RaceCar temp = a;   // Copy constructor gets called (see comment on standard) 
a = b;          // operator=
b = temp;       // operator= 

默认复制构造函数,只是逐个复制成员,所以只是复制指针。所以最后,你的temp和你会尝试删除两次指向的相同对象。

赋值初始化式注释:
对于类型T,形式T a = b;的语句是初始化式。
ISO标准c++第12.6.1节第1点解释了"单个赋值表达式可以使用初始化的=形式指定为初始化式。""