我试图实现Vector的一个函数,即Resize 据我所知,我实现的所有其他功能都很好
在测试代码中,我试图打印出可能发生的每种可能情况,但是当我打印出新Vector的大小时(poitner为整数,称为_elements) 我收到错误"#。exr触发断点 由于我设置在循环中的测试者(主)的一些奇怪的原因" i< 8"它工作正常,但如果我做< =它触发它
我相信这是由调整大小功能引起的,但即使在调试器之后我似乎无法找到问题 (函数的表达式在代码中)
我创造的矢量成功地为那些可能想知道的人提供了智慧
为什么会这样?
具有以下输入/输出的功能是:
Vector::Vector(const Vector& other)
{
_elements = new int;
_size = other._size;
_capacity = other._capacity;
_resizeFactor = other._resizeFactor;
for (int i = 0; i < _size; ++i)
{
_elements[i] = other._elements[i];
}
}
//change _size to n, unless n is greater than the vector's capacity
//same as above, if new elements added their value is val
void Vector::resize(int n, const int& val)
{
if (n <= _capacity)
{
while (n < _size)
{
pop_back();
}
while (n > _size)
{
push_back(val);
}
_capacity = n;
}
else if (n > _capacity)
{
reserve(n);
while (n > _size)
{
push_back(val);
}
}
}
//change the capacity
void Vector::reserve(int n)
{
if (n > _capacity)
{
int size = _resizeFactor;
while (n - _capacity > size)
{
size = size + _resizeFactor;
}
_capacity += size;
}
}
//adds element at the end of the vector
void Vector::push_back(const int& val)
{
if (_size < _capacity)
{
_elements[_size] = val;
_size++;
}
else if (_size == _capacity)
{
int* a = new int[_capacity + _resizeFactor];
for (int i = 0; i < _size; i++)
{
a[i] = _elements[i];
}
_capacity += _resizeFactor;
_elements = new int[_capacity];
for (int i = 0; i < _size; i++)
{
_elements[i] = a[i];
}
delete a;
_elements[_size] = val;
_size++;
}
}
void Vector::pop_back()
{
if (_size > 0)
{
_elements[_size] = NULL;
_size--;
}
}
我用
检查void print(const Vector& p)
{
cout << "Size = " << p.size() << ", Capacity = " << p.capacity() << ", isEmpty = " << (p.empty() ? "True" : "False") << endl;
}
并在主要:
Vector a(10);
for (int i = 0; i <= 8; i++)
a.push_back(i+1);
print(a);
a.push_back(10);
print(a);
a.push_back(11);
print(a);
int x = 99;
a.resize(a.capacity() + 11, x);
print(a);