更改数组类以容纳动态数组
Changing an array class to hold a dynamic array
我读到的所有内容都说这应该很容易,你只需添加这三行
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;
}
}
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结