0

これが私の構造です:

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から「sort」関数に渡すために使用する述語関数です。

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

並べ替え関数のコメントを外すと、コードが壊れます。構造内の動的配列のせいだと思います。(実際には配列をソートしますが、「形状」配列は構造とは別に壊れています。)ありがとう:)

4

1 に答える 1

2

デストラクタが一時オブジェクトで呼び出されています:

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

コピーコンストラクター、ムーブコンストラクター、コピー代入演算子、ムーブ代入演算子を作成するか、マネージドコンテナーに置き換えることにより、5つのルールを尊重する必要があります。shapestd::vector<std::vector<int>>

于 2012-10-22T09:36:12.840 に答える