gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:03:11 27 4
gpt4 key购买 nike

这是我的结构:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com