簡體   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