user1120144
user1120144

Reputation:

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

Here's my structure:

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

I have an array of such structures and I want to sort that array in ascending order by the "force". Here's my array and the predicate function I use to pass to the "sort" function from the 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);

When I uncomment the sort function the code breaks. I think it's because of the dynamic arrays inside the structures. (It actually sorts the array but the "shape" arrays are broken iside the structures.) Thanks :)

Upvotes: 0

Views: 472

Answers (1)

ecatmur
ecatmur

Reputation: 157334

Your destructor is being called on temporary objects:

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

You need to respect the Rule of Five, either by writing a copy constructor, move constructor, copy assignment operator and move assignment operator, or by replacing shape with a managed container e.g. std::vector<std::vector<int>>.

Upvotes: 2

Related Questions