繁体   English   中英

如何在C ++中对包含动态数组的结构数组进行排序?

[英]How to sort an array of structs that contain dynamic arrays in C++?

这是我的结构:

struct animal
{
    int position;
    int** shape;
    int rows, cols;
    int force;
    int minSafety;
    void init(int r,int c,int k, int t, int p)
    {
        shape = new int*[r];
        for(int i = 0; i < r; i++)
        {
            shape[i] = new int[c];
        }
        rows = r;
        cols = c;
        force = k;
        minSafety = t;
        position = p;
    }
    ~animal()
    {
        for(int i = 0; i < rows; i++)
        {
            delete[] shape[i];
        }
        delete[] shape;
    }
};

我有一个这样的结构数组,我想通过“force”按升序对该数组进行排序。 这是我的数组和谓词函数,我用它传递给STL的“排序”函数。

bool sortByForce(animal& animal1, animal& animal2)
{
    return animal1.force !=  animal2.force ?
        animal1.force < animal2.force : animal1.rows * animal1.cols > animal2.rows * animal2.cols;
}
animal* animals = new animal[P];
//sort(animals, animals+P, &sortByForce);

当我取消注释sort函数时代码中断了。 我认为这是因为结构内部的动态数组。 (它实际上对数组进行了排序,但“形状”数组在结构中被破坏了。)谢谢:)

你的析构函数是在临时对象上调用的:

animal a;
a.init(...);
{
    animal tmp = a;
} // tmp destructor called, frees memory belonging to a

您需要遵守五条规则 ,通过编写复制构造函数,移动构造函数,复制赋值运算符和移动赋值运算符,或者使用托管容器替换shape ,例如std::vector<std::vector<int>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM