更改数组类以容纳动态数组

Changing an array class to hold a dynamic array

本文关键字:数组 动态      更新时间:2023-10-16

我读到的所有内容都说这应该很容易,你只需添加这三行

typedef double* DoublePtr;
  DoublePtr p;
  p = new double [10]

但是我该把这个代码添加到哪里呢?我所尝试的一切都破坏了我的程序,我错过了什么?我尝试了一个set函数来设置最大大小的值,但也不起作用有人知道怎么做吗?

#include<iostream>
using namespace std;
const int MAX_SIZE = 50;
class ListDynamic
{
    public:
        ListDynamic();
        bool full();
        int getSize();
        void addValue(double value);
        double getValue(int index);
        double getLast();
        void deleteLast();
        friend ostream& operator <<(ostream& out, const ListDynamic& thisList);  
    private:
        double listValues[MAX_SIZE];
        int size;
};
int main()
{
    double value;
    ListDynamic l;
    cout << "size of List " << l.getSize() << endl;

    cout << "New size of List " << l.getSize() << endl;
    cout << "First Value: " << l.getValue(0) << endl;
    cout << "Last Value: " << l.getLast() << endl;
    cout << "deleting last value from list" << endl;
    l.deleteLast();
    cout << "new list size "  << l.getSize() << endl;
    cout << "the list now contains: " << endl << l << endl;
    system("pause");
    return 0;
}
ListDynamic::ListDynamic()
{
    size = 0;
}
bool ListDynamic::full()
{
    return (size == MAX_SIZE);
}
int ListDynamic::getSize()
{
    return size;
}
void ListDynamic::addValue(double value)
{
    if (size < MAX_SIZE)
    {
        listValues[size] = value;
        size++;
    }
    else
        cout << "nn*** Error in ListDynamic Class: Attempting to add value past max limit.";
}
double ListDynamic::getValue(int index)
{
    if (index < size)
        return listValues[index];
    else
        cout << "nn*** Error in ListDynamic Class: Attempting to retrieve value past current size.";
}
double ListDynamic::getLast()
{
    if (size > 0)
        return getValue(size - 1);
    else
        cout << "nn*** Error in ListDynamic Class: Call to getLast in Empty List.";
}
void ListDynamic::deleteLast()
{
    if (size > 0)
        size--;
    else
        cout << "nn*** Error in ListDynamic Class: Call to deleteLast in Empty List.";
}
ostream& operator <<(ostream& out, const ListDynamic& thisList)
{
    for (int i = 0; i < thisList.size; i++)
        out << thisList.listValues[i] << endl;
    return out;
}  

您需要将listValues更改为double*

double* listValues;

当您添加一个大于大小的值时,您需要将数组重新分配给您的数组,并将前一个数组的元素复制到新的数组中。例如:

void ListDynamic::addValue(double value)
{
    if (full())
    {
        double* temp = new double[size];
        std::copy(listValues, listValues + size, temp);
        delete[] listValues;
        listValues = new double[size + 1];
        std::copy(temp, temp + size, listValues);
        listValues[size] = value;
        delete[] temp;
    } else
    {
        listValues[size++] = value;
    }
}