我想通过使用静态数组来模拟动态数组。但是,当我从数组中删除一些元素然后尝试添加数组时,我收到一条错误,上面写着“检测到堆腐败”。
这是我的代码:
#include <iostream>
#include <algorithm>
using namespace std;
int INIT_SIZE = 5;
int MAX_SIZE = INIT_SIZE;
void printArray(int *arr, int n){
cout << "n= " << n << " >> [";
for(int i = 0; i < n ;i++){
cout << arr[i];
if ( i < n-1)
cout << ",";
}
cout << "]\b\n";
}
bool deleteEl(int *&arr, int &n, int el){
int *newArr;
bool found = false;
int cnt = 0;
if( n == 0){
return false;
}
else{
for(int i = 0; i < n;i++){
if( arr[i] == el){
found = true;
cnt++;
}
}
if( !found){
return false;
}
newArr = new int[n-cnt];
int k = 0;
for(int i = 0; i < n ; i++){
if( arr[i] != el){
newArr[k++] = arr[i];
}
}
n -= cnt;
if (n <= (MAX_SIZE / 2) && (MAX_SIZE / 2) >= INIT_SIZE){
MAX_SIZE /= 2;
}
delete[] arr;
arr = newArr;
}
return true;
}
bool addEl(int *&arr, int &n, int el){
int *newArr;
if( n >= MAX_SIZE){
newArr = new int[2 * MAX_SIZE];
//std::copy(arr,arr+MAX_SIZE, newArr);
for(int i = 0 ; i < n;i++){
newArr[i] = arr[i];
}
n++;
newArr[n-1] = el;
MAX_SIZE *= 2;
delete[] arr;
arr = newArr;
}else{
arr[n++] = el;
}
return true;
}
int main(int argc, char *argv[]){
int *arr = new int[MAX_SIZE];
int n = 0;
int input = 0;
do{
cout << "1. Add Element : " << endl;
cout << "2. Del Element : " << endl;
cout << "3. Exit : " << endl;
cin >> input;
if( input == 1){
cout << "Enter new element : " << endl;
int newEl;
cin >> newEl;
if( addEl(arr, n, newEl)){
cout << "New Element Added. " << endl;
}else{
cout << "Add new element failed. " << endl;
}
}else if (input == 2){
cout << "Enter deleted element : " << endl;
int del;
cin >> del;
if( deleteEl(arr, n, del)){
cout << "Deletion OK" << endl;
}else{
cout << "Deletion Fail. Data Not found." << endl;
}
}else if(input == 3){
cout << "Program exiting ..." << endl;
}else{
cout << "Input is wrong. Enter correct input (1,2, or 3)." << endl;
}
printArray(arr,n);
}while(input != 3);
delete [] arr;
return 0;
}