Adding to dynamic array

2019-07-08 06:47发布

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;
}

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).

So, what's wrong with this?

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.

1条回答
男人必须洒脱
2楼-- · 2019-07-08 07:20

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];

as opposed to:

T * tmp = new T[mCount];

If it's for anything else other than educational purposes, please use std::vector instead. For example your add function is not exception safe.

查看更多
登录 后发表回答