添加到动态数组 [英] Adding to dynamic array
问题描述
免责声明:是的,我知道std :: vector。我这样做是为了学习。
Disclaimer: Yes, I know about std::vector. I'm doing this for the sake of learning.
我正在制作一个动态数组类,并且正在尝试增加工作量。
I'm working on making a dynamic array class, and I'm trying to get add to work.
template <class T>
void Array<T>::add(T value)
{
T * tmp = new T[mCount];
for (int i = 0; i < mCount; i++)
{
tmp[i] = mData[i];
}
mCount++;
delete[] mData;
mData = tmp;
mData[mCount - 1] = value;
}
它的工作原理是……该函数可用于添加元素,但是退出时程序会崩溃。没有错误,什么都没有。它只是冻结,我必须使用(Shift + F5)将其关闭。
It works... sort of. The function works in adding the element, but then the program crashes when exiting. No errors, no nothing. It just freezes, and I have to close it using (Shift + F5).
那么,这怎么了?
这是我的全班。如果我不包含函数,则表示函数中没有代码。
Here's my whole class. If I didn't include a function it means there's no code in it.
#ifndef ARRAY_H
#define ARRAY_H
using namespace std;
template <class T>
class Array
{
private:
T * mData;
int mCount;
public:
Array();
~Array();
void add(T value);
void insert(T value, int index);
bool isEmpty();
void display();
bool remove(T value);
bool removeAt(int index);
int size();
T & operator[](const int index);
};
// Constructors / Destructors
// --------------------------------------------------------
template <class T>
Array<T>::Array()
{
mCount = 0;
mData = new T[mCount];
for (int i = 0; i < mCount; i++)
mData[i] = 0;
}
template <class T>
Array<T>::~Array()
{
delete[] mData;
}
// General Operations
// --------------------------------------------------------
template <class T>
void Array<T>::add(T value)
{
T * tmp = new T[mCount];
for (int i = 0; i < mCount; i++)
{
tmp[i] = mData[i];
}
mCount++;
delete[] mData;
mData = tmp;
mData[mCount - 1] = value;
}
template <class T>
void Array<T>::display()
{
if (isEmpty())
{
cout
<< "The array is empty."
<< "\n\n";
return;
}
cout << "(";
for (int i = 0; i < mCount; i++)
{
cout << mData[i];
if (i < mCount - 1)
cout << ", ";
}
cout << ")" << "\n\n";
}
template <class T>
bool Array<T>::isEmpty()
{
return mCount == 0;
}
template <class T>
int Array<T>::size()
{
return mCount;
}
// Operator Overloads
// --------------------------------------------------------
template <class T>
T & Array<T>::operator[](const int index)
{
return mData[index];
}
#endif
如果您需要任何其他信息
If you need any additional info lemme know and I can post it.
推荐答案
假设 mCount
保持数组中的元素数量,然后添加一个新元素时,您实际上必须分配至少 mCount + 1
个元素(假设您当然希望保留所有旧元素,新的):
Assuming mCount
keeps the number of elements in the array, then when adding a new element you really have to allocate at least mCount + 1
elements (assuming of course you want to keep all the old ones and the new one) via:
T * tmp = new T[mCount + 1];
相对于:
T * tmp = new T[mCount];
如果除教育目的外,还请使用 std ::向量
。例如,您的 add
函数不是异常安全的。
If it's for anything else other than educational purposes, please use std::vector
instead. For example your add
function is not exception safe.
这篇关于添加到动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!