#include <iostream>
using namespace std;
class _1DArray{
int size, *arr, index;
public:
_1DArray(){
this->size = 10;
this->index = 0;
arr = new int[size];
}
void insert(int n){
if(index < size){
arr[index++] = n;
}
else{
size *= 2;
arr = (int *) realloc(arr, size * sizeof(int));
arr[index++] = n;
}
}
void remove(){
if(size > 0){
cout<<"Deleting "<<arr[index - 1]<<endl;
arr = (int*) realloc(arr, index * sizeof(int));
size = index;
index--;
}
}
void show(){
for(int i = 0; i < index; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
};
class _2DArray{
int size, (*arr)[10], i, j;
public:
_2DArray(){
this->size = 10;
this->i = 0;
this->j = 0;
arr = new int[size][10];
}
void insert(int n){
if(j == 10){
j = 0;
i++;
}
if(j < 10 && i < size){
arr[i][j++] = n;
return;
}
if(i >= size){
size *= 2;
arr = (int (*)[10]) realloc(arr, size * sizeof(int[10]));
arr[i][j] = n;
}
}
void remove(){
if(size > 0){
j--;
if(j < 0){
j = 9;
i--;
}
if(i < 0) return;
if(i >= 0){
size = i + 1;
cout<<"Deleting "<<arr[i][j]<<endl;
arr[i][j] = -1;
arr = (int (*)[10]) realloc(arr, size * sizeof(int[10]));
}
}
}
void show(){
for(int k = 0; k < i + 1; k++){
for(int l = 0; l < 10; l++){
cout<<arr[k][l]<<" ";
}
cout<<endl;
}
}
};
int main(){
cout<<"Choose 1D or 2D array: (1 or 2)\n";
int c; cin>>c;
if(c == 1){
_1DArray arr;
cout<<"Inserting items\n";
while(c != -1){
cin>>c;
if(c != -1){
arr.insert(c);
cout<<"Contents\n";
arr.show();
}
}
cout<<"Deleting items\n";
cout<<"Input -1 to stop\n";
do{
cin>>c;
if(c != -1){
arr.remove();
cout<<"Contents\n";
arr.show();
}
}while(c != -1);
}
else if(c == 2){
_2DArray arr;
cout<<"Inserting items\n";
while(c != -1){
cin>>c;
if(c != -1){
arr.insert(c);
cout<<"Contents\n";
arr.show();
}
}
cout<<"Deleting items\n";
cout<<"Input -1 to stop\n";
do{
cin>>c;
if(c != -1){
arr.remove();
cout<<"Contents\n";
arr.show();
}
}while(c != -1);
}
return 0;
}
Comments
Leave a comment