这是我的结构:
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/