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

标签 c++ algorithm sorting struct

这是我的结构:

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

我有一个这样的结构数组,我想按“力”的升序对该数组进行排序。这是我的数组和我用来从 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);

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

最佳答案

正在对临时对象调用您的析构函数:

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

您需要尊重 Rule of Five ,通过编写复制构造函数、移动构造函数、复制赋值运算符和移动赋值运算符,或者通过替换 shape使用托管容器,例如std::vector<std::vector<int>> .

关于c++ - 如何在 C++ 中对包含动态数组的结构数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13008300/

相关文章:

algorithm - VF2 算法的任何工作示例?

arrays - Swift - 在数组中搜索数字模式

algorithm - 为学生分配伴侣的稳健算法

PHP 根据键排序数组,顺序为字母顺序,然后是数字,然后是特殊字符

linux - 在 bash 脚本中将列转换为行

javascript - 如何对数组中高于阈值的元素进行平均?

c++ - C++ 中的简单警告框,而不是 Objective-C

c++ - 在用户机器上存储 key 的推荐方法

c++ - gcc 和 clang 预处理器不理解 L 前缀

c++ - QFileDialog打开多个文件