【问题标题】:Adding to dynamic array添加到动态数组
【发布时间】:2015-10-10 22:40:47
【问题描述】:

免责声明:是的,我知道 std::vector。我这样做是为了学习。

我正在制作一个动态数组类,并且正在尝试添加到工作中。

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) 关闭它。

那么,这有什么问题呢?

这是我的整个班级。如果我没有包含函数,则表示其中没有代码。

#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

如果您需要任何其他信息,请告诉我,我可以发布。

【问题讨论】:

  • OT,但为什么不使用 std::vector?
  • @MrTux,用于教育目的
  • 在数组声明中肯定需要 mcount + 1 以避免数组越界异常
  • 第一个错误在add函数中。将代码更改为T * tmp = new T[mCount + 1];
  • mCount 的不变量是什么?

标签: c++ class templates dynamic-arrays


【解决方案1】:

假设mCount 保留了数组中的元素数量,那么在添加新元素时,您确实必须至少分配mCount + 1 元素(当然假设您希望保留所有旧元素和新元素)通过:

T * tmp = new T[mCount + 1];

相对于:

T * tmp = new T[mCount];

如果用于教育目的以外的任何其他用途,请改用std::vector。例如,您的 add 函数不是异常安全的。

【讨论】:

  • 实际上应该分配 2*mcount 个元素。
  • 哇,谢谢。我喜欢解决方案就在我的眼皮底下,但我看不到它。一旦它让我接受你的答案,我会的。
  • 我宁愿将mCount的增量移到函数的开头。
  • @Zereges 可能希望保留旧值,直到您再次获得良好状态。如果分配失败怎么办?
  • @PeterSchneider 好吧,如果 alloc 失败了,你就完蛋了:)
猜你喜欢
  • 2014-09-06
  • 2020-04-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多