繁体   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