【发布时间】:2021-11-03 03:45:26
【问题描述】:
我有一个任务是在名为 insert 和 print 的数组类中创建两个函数。插入应该将元素添加到数组的末尾,当我运行代码时,我得到的输出对于第二个数组来说看起来不错,但第一个数组给出了奇怪的输出。我真的不知道从这里去哪里,任何指针都有帮助
#include <iostream>
using namespace std;
class Array //The array class
{
private:
//Data members capacity, size, and arr (a pointer that points to the first element of the array in the heap).
int capacity{};
int size{};
int* arr{};
public:
Array(int capacity);//parameter
Array();//default
~Array();//destructor
void insert(int num);
void print() const ;
};
void Array::insert(int num)
{
{
if (size == 0)
{
arr[0] = num;
size++;
return;
}
int index = 0;
while (num > arr[index] && index < size)
{
index++;
}
arr[index] = num;
size++;
}
}
void Array::print() const
{`enter code here`
for (int i = 0; i < size; i++)
{
cout << *(arr+i)<<" ";
}
delete[]arr;
}
Array::Array()
{
return;
}
//Destructor to clean up
Array::~Array()
{
return;
}
//Parameter constructor
Array::Array(int cap)
:capacity(cap)
{
arr = new int[capacity];
size = 0;
}
int main()
{
// Creation of an array with a capacity of 10
Array array1(10);
array1.insert(5);
array1.insert(3);
array1.insert(2);
cout << "Array 1: " << endl;
array1.print();
cout << endl;
// Creation of another array
Array array2(20);
for (int i = 0; i < 20; i++)
{
array2.insert(i + 10);
}
cout << "Array 2: " << endl;
array2.print();
cout << endl;
return 0;
}
【问题讨论】:
-
如果你的数组有
size元素,它的结尾索引是多少? -
很抱歉,显示的代码中有很多错误,很难知道从哪里开始。请注意,在
Array::Array()中,您不会创建数组。在insert中,当大小达到容量时,您永远不会增加阵列。析构函数为空,而它应该删除数组。您的打印功能会删除数组。所有这些都是严重错误。首先确保您了解new[]和delete[]的作用,以及构造函数和析构函数的用途。 -
谢谢我通过将删除移动到析构函数、初始化分配的数组以及将删除数组移出打印函数来解决一些错误。我现在得到 2 0 0 的 Array1 输出,这是朝着正确方向迈出的一步,因为我不再获得垃圾值
-
感谢您的帮助,我能够正确打印出数字
标签: c++ arrays c++11 heap-memory