【发布时间】:2021-02-22 17:41:34
【问题描述】:
在我的 Comp Sci 课程中,我们正在学习如何制作自己的矢量类。我们最终会将我们定制的字符串类对象存储在定制的向量类中。为了简单起见,我想尝试预先构建一个整数向量类。
到目前为止,我有一个默认构造函数,它将我的指针初始化为一个空数组并将大小设置为 0。然后我尝试使用我的 push_back 函数附加一些值,然后检查以确保它正确完成。
当我做 std::cout
我得到正确的输出 (10)。但是,如果我再次调用 push_back 然后调用 v[1] 我得到 0。
我觉得我在 push_back 函数中没有正确分配内存,但我不确定。
感谢您的建议!
[第 1 部分][1]
[第 2 部分][2]
对不起,如果我的格式有误,我是新来这里发帖的。
类:
class myVector
{
private:
int *data; //will point to an array of ints
size_t size; //determins the size of array
public:
myVector(); // default constructor
void push_back(int); // appends an integer to the vector
int operator[](size_t);
size_t sizeOf();
};
主要:
int main()
{
myVector v;
v.push_back(10);
std::cout << v.sizeOf() << std::endl;
v.push_back(14);
std::cout << v.sizeOf() << std::endl;
std::cout << v[1] << std::endl;
return 0;
}
成员函数:
size_t myVector::sizeOf()
{
return size;
}
int myVector::operator[](size_t location)
{
return this->data[location]; //this will return the value at data +
//location
}
myVector::myVector()
{
this->data = new int[0]; //initialize the data to an empty array of
//ints
size = 0; //initialize the size to 0
}
void myVector::push_back(int val)
{
if(size == 0) //if size == 0, create a new array with 1 extra index
{
++size;
delete [] this->data;
this->data = new int[size];
this->data[0] = val;
}
else
{
++size;
int *temp = new int[size - 1];
for(int i = 0; i != (size - 1); i++)
{
temp[i] = this->data[i];
}
delete [] this->data;
this->data = new int[size];
for(int i = 0; i != (size - 1); i++)
{
this->data[i] = temp[i];
}
this->data[size] = val;
delete [] temp;
}
}
【问题讨论】:
-
请在问题中包含minimal reproducible example。请以文本而不是图像的形式编码
-
我很抱歉,试图让格式正确到足以提交是很烦人的。但现在它起来了!
-
你从
size=0开始,然后你增加大小并通过new int[size -1]分配一个数组,对于1个元素来说仍然不够大。 -
@idclev463035818 这实际上不是问题,因为稍后会有 second 分配
this->data = new int[size]。在这段代码中,new和delete[]的用法太多了,但实际上并没有导致这个特定问题。 -
@NathanPierson 哦,对了,谢谢。所看到的只是将元素存储在某个临时数组中(无论出于何种原因),我只是看到了,并没有继续阅读。
标签: c++ arrays class pointers dynamic-memory-allocation