zybook c++ please help me in the easiest way to understand. Books My library >CO
ID: 3755467 • Letter: Z
Question
zybook c++
please help me in the easiest way to understand.
Explanation / Answer
Please find the code below.
CODE
===============
#include <iostream>
#include <string>
using namespace std;
class DynamicArray {
public:
int *arr;
int arraySize;
int numOfElements;
DynamicArray(int size) {
if (size < 1) {
arraySize = 1;
} else {
arraySize = size;
}
arr = new int[arraySize];
numOfElements = 0;
}
DynamicArray(const DynamicArray &a) {
arraySize = a.arraySize;
numOfElements = a.numOfElements;
arr = new int[arraySize];
for(int i=0; i<numOfElements; i++) {
arr[i] = a.arr[i];
}
}
int getArraySize() {
return arraySize;
}
int getNumOfElements() {
return numOfElements;
}
string print() {
if (numOfElements == 0) {
return "No element";
}
string res = "";
for(int i=0; i<numOfElements - 1; i++) {
res += to_string(arr[i]) + ", ";
}
res += to_string(arr[numOfElements - 1]);
return res;
}
void addElement(int num) {
if (numOfElements >= arraySize) {
int *temp = new int[2*arraySize];
for(int i=0; i<numOfElements; i++) {
temp[i] = arr[i];
}
arraySize = 2*arraySize;
arr = new int[arraySize];
for(int i=0; i<numOfElements; i++) {
arr[i] = temp[i];
}
delete[] temp;
}
arr[numOfElements ++] = num;
}
void deleteElement(int num) {
int found = 0;
for(int i=0; i<arraySize; i++) {
if(arr[i] == num) {
for(int j=i; j<(arraySize-1); j++) {
arr[j]=arr[j+1];
}
found = 1;
}
if(found == 1) {
numOfElements --;
break;
}
if (numOfElements <= arraySize/2) {
int *temp = new int[arraySize/2];
for(int i=0; i<numOfElements; i++) {
temp[i] = arr[i];
}
arraySize = arraySize/2;
arr = new int[arraySize];
for(int i=0; i<numOfElements; i++) {
arr[i] = temp[i];
}
delete[] temp;
}
}
}
~DynamicArray() {
delete[] arr;
}
};
NOTE: Due to lack of time, I could not implement the bonus method. Please post the bonus method separately and I will try to answer it. And, if any of the test methods in main() fails, please reach out to me.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.