簡體   English   中英

C ++,我需要能夠調整動態數組的大小

[英]C++ I need to be able to resize my dynamic array

我有一個動態數組的代碼,我是在實驗中上交的。 我的老師回答說“甚至不會編譯,也不會調整數組的大小”。 我在處理“不調整數組大小”的注釋時遇到麻煩,這意味着我必須添加調整數組大小的功能。 請快速幫助! (它確實可以編譯)。 欣賞它。

我應該做一個程序,要求用戶最初調整數組大小。 根據該大小創建一個數組,要求輸入數字,然后插入數字。 然后重復獲取並插入一個數字,根據需要調整數組的大小,或者直到輸入數字-1為止。 打印列表。

#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;
}

當陣列已滿時,我們需要調整其大小。 這是我的解決方案

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM