Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the bag from Chapter 4 (using a dynamic array). The pointer to the dyna

ID: 3671352 • Letter: C

Question

Consider the bag from Chapter 4 (using a dynamic array). The pointer to the dynamic array is called data, and the size of the dynamic array is stored in a private member variable called capacity. Write the following new member function: (C++ LANGUAGE)

    void bag::triple_capacity( )

    // Postcondition: The capacity of the bag's dynamic array has been

    // tripled. The bag still contains the same items that it previously

    // had.

Do not use the reserve function, do not use realloc, and do not cause a heap leak. Do make sure that both data and capacity have new values that correctly indicate the new larger array.

Explanation / Answer

Comments added ...

void bag::triple_capacity()
{
//first declare new fresh array with triple size
int* newArray = new int[3*capacity];

//copy the past array elements to new array
for(int i=0;i<capacity;i++){
newArray[i] = data[i];
}

//deleting the old array data.. or freeing the array memory
delete[] data;

// again making new increased array as old array
data = newArray;

//increasing size
capacity = capacity*3;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote