mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
Add destructors to the C++ codes.
This commit is contained in:
@@ -23,6 +23,8 @@ int* extend(int* nums, int size, int enlarge) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// 释放内存
|
||||
delete[] nums;
|
||||
// 返回扩展后的新数组
|
||||
return res;
|
||||
}
|
||||
@@ -82,10 +84,7 @@ int main() {
|
||||
|
||||
/* 长度扩展 */
|
||||
int enlarge = 3;
|
||||
int* res = extend(nums, size, enlarge);
|
||||
int* temp = nums;
|
||||
nums = res;
|
||||
delete[] temp;
|
||||
nums = extend(nums, size, enlarge);
|
||||
size += enlarge;
|
||||
cout << "将数组长度扩展至 8 ,得到 nums = ";
|
||||
PrintUtil::printArray(nums, size);
|
||||
@@ -107,5 +106,9 @@ int main() {
|
||||
int index = find(nums, size, 3);
|
||||
cout << "在 nums 中查找元素 3 ,得到索引 = " << index << endl;
|
||||
|
||||
// 释放内存
|
||||
delete[] arr;
|
||||
delete[] nums;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -83,5 +83,8 @@ int main() {
|
||||
int index = find(n0, 2);
|
||||
cout << "链表中值为 2 的结点的索引 = " << index << endl;
|
||||
|
||||
// 释放内存
|
||||
freeMemoryLinkedList(n0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,11 @@ public:
|
||||
nums = new int[numsCapacity];
|
||||
}
|
||||
|
||||
/* 析构函数 */
|
||||
~MyList() {
|
||||
delete[] nums;
|
||||
}
|
||||
|
||||
/* 获取列表长度(即当前元素数量)*/
|
||||
int size() {
|
||||
return numsSize;
|
||||
@@ -90,14 +95,14 @@ public:
|
||||
void extendCapacity() {
|
||||
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
|
||||
int newCapacity = capacity() * extendRatio;
|
||||
int* extend = new int[newCapacity];
|
||||
int* tmp = nums;
|
||||
nums = new int[newCapacity];
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for (int i = 0; i < size(); i++) {
|
||||
extend[i] = nums[i];
|
||||
nums[i] = tmp[i];
|
||||
}
|
||||
int* temp = nums;
|
||||
nums = extend;
|
||||
delete[] temp;
|
||||
// 释放内存
|
||||
delete[] tmp;
|
||||
numsCapacity = newCapacity;
|
||||
}
|
||||
|
||||
@@ -160,5 +165,8 @@ int main() {
|
||||
PrintUtil::printVector(vec);
|
||||
cout << "容量 = " << list->capacity() << " ,长度 = " << list->size() << endl;
|
||||
|
||||
// 释放内存
|
||||
delete list;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user