简体   繁体   中英

C++ I need to be able to resize my dynamic array

I have this code of a dynamic array that I turned in as a lab. My instructor responded saying "wouldn't even compile, no resize of the array". I am having trouble dealing with the comment of "no resize of the array", meaning I have to add the ability to resize the array. Please help quick! (It does compile). Appreciate it.

I am supposed to make a program that asks the user to initially size the array. Create an array based on that size asking for a number, and insert the number. Then repeat getting and inserting a number, resizing the array as needed or until they enter -1 for the number. Print the list.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int count;
    cout << "How many values do you want to store in your array?" << endl;
    cin >> count;
    int* DynamicArray;
    DynamicArray = new int[count];

    for (int i = 0; i < count; i++) {
        cout << "Please input Values: " << endl;
        cin >> DynamicArray[i];

        {
            if (DynamicArray[i] == -1) {
                delete[] DynamicArray;
                cout << "The program has ended" << endl;
                exit(0);
            }
            else {
                cout << endl;
            }
        }
    }
    for (int k = 0; k < count; k++) {
        cout << DynamicArray[k] << endl;
    }

    delete[] DynamicArray;
    return 0;
}

When the array is full, we need to resize it. Here is my solution

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main()
{
    int count;
    cout << "How many values do you want to store in your array?" << endl;
    cin >> count;
    if (count <= 0) {
        cout << "The value should be greater than zero" << endl;
        exit(0);
    }
    int* DynamicArray;
    DynamicArray = new int[count];

    int i = 0, value = 0;
    while (1) {
        cout << "Please input Values: " << endl;
        cin >> value;

        if (value == -1) {
                cout << "The program has ended" << endl;
                break;
        }
        else if (i < count)
        {
            DynamicArray[i++] = value;
        }
        else
        {
            // resize the array with double the old one
            count = count * 2;
            int *newArray = new int[count];
            memcpy(newArray, DynamicArray, count * sizeof(int));
            delete[]DynamicArray;
            newArray[i++] = value;
            DynamicArray = newArray;
        }
    }
    for (int k = 0; k < i; k++) {
        cout << DynamicArray[k] << endl;
    }

    delete[] DynamicArray;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM