0

好的,伙计们,所以我正在实现一个类 Matrix(就像线性代数中的矩阵),当抛出异常时,我遇到了一个特殊情况的奇怪问题。当用户被要求从控制台输入矩阵数据时,如果 !first! 则程序崩溃。输入是触发类抛出异常的东西。我想这一定是某种我无法追踪的奇怪内存泄漏。

该类的唯一私有成员是 :double** rows// int widthint height我将向您展示我的类析构函数、导致问题的输入函数以及我的主要函数:

〜矩阵()

Matrix::~Matrix()
{
    if (rows)
    {
        for (int k = 0; k < height; k++)
        {
            delete[] rows[k];
        }
        delete[] rows;
        rows = 0;
    }
}

运算符>>重载

std::istream& operator>> (std::istream& in, Matrix &obj)
{
    if (obj.rows)
    {
        for (int i = 0; i < obj.height; i++)
        {
            delete[] obj.rows[i];
        }
        delete[] obj.rows;
        obj.rows = 0;
        obj.width = 0;
        obj.height = 0;
    }
    std::cout << "Input matrix data (enter 'q' to stop and 'n' to start new row):" << std::endl;
    std::string input = "";
    double data;
    obj.height = 1;
    obj.rows = new double* [obj.height];
    int temp_width = 0;                                  // can overflow for incredibily long rows ;Ds
    double* temp_row = 0;
    while (true)
    {
        std::cin >> input;
        std::istringstream inputStream(input);
        //fill current row
        if (inputStream >> data)
        {
            temp_width++;
            if (temp_width > obj.width)
            {
                obj.width = temp_width;
            }
            if (temp_width == 1)
            {
                obj.rows[obj.height - 1] = new double[temp_width];
                obj.rows[obj.height - 1][temp_width - 1] = data;
            }
            else //(temp_width > 1)
            {
                //store row without the new element
                temp_row = new double [temp_width - 1];
                for (int j = 0; j < temp_width - 1; j++)
                {
                    temp_row[j] = obj.rows[obj.height - 1][j];
                }
                //temp_row = obj.rows[obj.height - 1];
                delete[] obj.rows[obj.height - 1];
                obj.rows[obj.height - 1] = 0;   //probably not needed
                obj.rows[obj.height - 1] = new double[temp_width];

                //copy over the row from previous iteration
                for (int k = 0; k < temp_width - 1; k++)
                {
                    obj.rows[obj.height - 1][k] = temp_row[k];
                }
                //append the new element at the end of current row
                obj.rows[obj.height - 1][temp_width - 1] = data;
                delete[] temp_row;
                temp_row = 0;
            }
        }
        //add new row
        else if (input == "n")
        {
            //prevent creating new row if the current one is empty
            if (temp_width == 0)
            {
                throw InputError("You must enter at least one element per row.");
            }
            //stuff end of row with zeroes if needed
            else if (temp_width < obj.width)
            {
                temp_row = new double [temp_width];
                temp_row = obj.rows[obj.height - 1];
                delete[] obj.rows[obj.height - 1];
                obj.rows[obj.height - 1] = new double[obj.width];
                for (int i = 0; i < obj.width; i++)
                {
                    if (i > temp_width - 1)
                        obj.rows[obj.height - 1][i] = 0;
                    else
                        obj.rows[obj.height - 1][i] = temp_row[i];
                }
                delete[] temp_row;
                temp_row = 0;
            }
            //backup current matrix AND delete the original
            double** temp_matrix = new double* [obj.height];
            for (int k = 0; k < obj.height; k++)
            {
                temp_matrix[k] = new double [obj.width];
                for (int j = 0; j < obj.width; j++)
                {
                    temp_matrix[k][j] = obj.rows[k][j];
                }
                delete[] obj.rows[k];
            }
            delete[] obj.rows;
            obj.rows = 0;
            //generate the new bigger matrix, copy backup into it, delete backup
            obj.height++;
            obj.rows = new double* [obj.height];
            for (int s = 0; s < obj.height - 1; s++)
            {
                obj.rows[s] = new double [obj.width];
                for (int v = 0; v < obj.width; v++)
                {
                    obj.rows[s][v] = temp_matrix[s][v];
                }
                delete[] temp_matrix[s];
            }
            delete[] temp_matrix;
            temp_matrix = 0;
            temp_width = 0;
        }
        //exit input
        else if (input == "q")
        {
            if (obj.width == 0)
            {
                throw InputError("Input Error. You must enter at least one element into matrix");
            }
            //stuff with zeroes if needed
            if (temp_width < obj.width)
            {
                temp_row = new double [temp_width];
                temp_row = obj.rows[obj.height - 1];
                delete[] obj.rows[obj.height - 1];
                obj.rows[obj.height - 1] = new double[obj.width];
                for (int i = 0; i < obj.width; i++)
                {
                    if (i > temp_width - 1)
                        obj.rows[obj.height - 1][i] = 0;
                    else
                        obj.rows[obj.height - 1][i] = temp_row[i];
                }
            }
            break;
        }
        //throw input error
        else
        {
            throw InputError("Input Error. Only numbers and the characters 'n' and 'q' are accepted");
        }
    }
    return in;
}

主要的()

int main()
{
    bool tryAgain = true;
    Matrix m1;
    while (tryAgain)
    {
        try
        {
            cin >> m1;
            cout << "Matrix 1: \n" << m1;
        }
        catch (InputError& e)
        {
            cout << e.what() << endl;
        }
        cout << "Enter matrix data again? (y/n) ";
        char input;
        cin >> input;
        if (input == 'n') tryAgain = false;
    }
    return 0;
}

如果您觉得彻底查看我的 operator>> 功能太麻烦,请以程序崩溃的最简单情况为例。那是当用户的第一个输入不是数字或字符 'q' 和 'n' 之一时。这由 operator>> 函数中的最后一个 else 语句处理。确切的结果是,在控制台中您会看到抛出的异常,然后 main() 函数的 while 循环继续。当它第二次循环回到cin >> m1;语句时,无论输入如何,您都会收到一条消息 - “此应用程序已请求运行时终止它......”。有时您甚至不必第二次输入任何内容,并且在此之前它会崩溃。有任何想法吗?

4

2 回答 2

2

您遇到的问题归结为您的内存管理选择,我认为这从根本上是不正确的,因为您不是在建模矩阵,而是对具有全部非连续内存负载的锯齿状结构进行建模。(例如,编写转置方法对于您的设计选择来说将是一场噩梦。)

从这里出发的两条路线:

1)用一块内存重新设计你的类;建议将(从零开始的)元素 (i, j) 保存在 i * rows + j 处,其中 rows 是矩阵中的行数。double& operator()(unsigned i, unsigned j)您可以将 [][] 替换为对表单和的重载运算符的调用const double& operator()(unsigned i, unsigned j) const。(提供了参考,因此您可以使用 (,) 作为左值;例如myMatrixObject(i, j) = 1.0

2) 使用 BLAS 中的矩阵类(可在 www.boost.org 获得)。其中包含实现,除其他外,稀疏矩阵和单位矩阵。

我更喜欢(2)。我知道构建自己的矩阵类很有趣,但“不要重新发明轮子”确实浮现在脑海中。

于 2013-07-02T15:40:37.287 回答
0

使用向量。他们管理自己的内存,测试溢出并轻松允许您添加新元素。在这种情况下,您需要一个向量向量来表示二维数组。我懒得为你把它包装在一个类中,但这是基本的想法。

vector< vector< double > > data;
// height
data.resize(10);
// width
for (vector< vector< double > >::iterator it = data.begin(), end_it = data.end(); it != end_it; ++it)
{
    it->resize(5);
}

// access element, notice X/Y reversed (it's more efficient this way)
int x = 3;
int y = 4;
double d = data[y][x];

// add extra element to row
data[y].push_back(d);
于 2013-07-02T17:27:54.253 回答