作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
抱歉,如果之前已经回答过这个问题。我搜索了调整动态数组的大小,所有的建议似乎都是使用 STL Vector,但我正在做一个任务,重点是制作我自己的最小 vector 模板类。
我的 vector 类需要存储从输入文件中读取而创建的动态结构数组。它必须做的一件事是在满时调整大小。它工作到一定程度 - 处理 52207 行中的 5121 行,然后崩溃并出现错误“进程返回 -1073741819 (0XC0000005)”。
我环顾四周,发现这是一个内存分配错误。我是编程和 C++ 的新手,我对我的程序中的原因感到困惑。我假设它在我调整数组代码的大小中。任何帮助将不胜感激!
我的 vector 模板代码:
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
template <class T>
class Vector {
public:
/// Constructor
Vector();
/// Copy constructor
Vector(const Vector<T>& otherVector);
/// Destructor
virtual ~Vector();
/// assignment operator
const Vector<T>& operator= (const Vector<T>&);
/// methods
void addElement(const T& newElement);
T getElement(int index) const;
int getLength() const;
protected:
int arraySize;
int length;
T *p;
};
template <class T>
Vector<T>::Vector()
{
arraySize = 10;
length = 0;
p = new T[arraySize];
}
template <class T>
Vector<T>::Vector(const Vector& otherObject)
{
arraySize = otherObject.arraySize;
length = otherObject.length;
p = new T[arraySize];
for(int i = 0; i < length; i++)
p[i] = otherObject.p[i];
}
template <class T>
Vector<T>::~Vector()
{
delete [] p;
}
template <class T>
const Vector<T>& Vector<T>::operator= (const Vector<T>& newVector)
{
if(this != &newVector)
{
delete [] p;
arraySize = newVector.arraySize;
length = newVector.length;
p = new T[arraySize];
for(int i = 0; i < length; i++)
p[i] = newVector.p[i];
}
return *this;
}
template <class T>
void Vector<T>::addElement(const T& newElement)
{
if(length == arraySize)
{
// create a new resized array
T *temp;
temp = new T[arraySize*2];
// copy elements of p into temp
for(int i = 0; i < length; i++)
{
temp[i] = p[i];
}
// delete p and create new p and set equal to temp
delete [] p;
arraySize *= 2; // set array size to double
p = new T[arraySize];
p = temp;
// delete temp array
delete [] temp;
// add new element and incerement length;
p[length] = newElement;
length++;
}
else
{
p[length] = newElement;
length++;
}
}
template <class T>
T Vector<T>::getElement(int index) const
{
return p[index];
}
template <class T>
int Vector<T>::getLength() const
{
return length;
}
#endif
最佳答案
您的调整大小逻辑有误。在您到达这里之前,一切都很好。
p = new T[arraySize];
p = temp;
delete [] temp;
您分配一个新数组,然后立即让 p
指向 temp
指向的数据。然后删除 temp
指向的数据,它与 p
相同,这意味着 p
指向释放的内存;它是一个悬空引用,未定义通过 p
不过修复起来很简单:去掉分配和删除,只需要有赋值的那一行:
// p = new T[arraySize];
p = temp;
// delete [] temp;
p
不需要新空间,temp
已经有了。只需将它交给 p
。然后你不删除 temp
,因为 p
正在管理它。
关于C++ 调整动态数组的大小最多可以处理一定数量的元素,但有时会因错误 (0XC0000005) 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085136/
我正在尝试开发右边框/Angular 具有特定 Angular (30°) 的表格。我见过一些类似的解决方案,但它们都无法在一定程度上发挥作用。如果我想从 30° 改变到 20°,我不想花太多力气。
我是一名优秀的程序员,十分优秀!