初始化不起作用

Initialization not Working

本文关键字:不起作用 初始化      更新时间:2023-10-16

我正在尝试解决C++中的最短路径问题。为此,我创建了以下Graph()构造函数。

Graph::Graph(int NumberOfVertices){
    this->NumberOfVertices=NumberOfVertices;
    cout<<"Graph()"<<endl;
    //declaring the weight matrix
    WeightMatrix=new int*[NumberOfVertices];
    for(int a=0;a<NumberOfVertices;a++)
        WeightMatrix[a]=new int[NumberOfVertices];
   //initialising the weight matrix
    WeightMatrix[NumberOfVertices][NumberOfVertices]={0};
    ShortestPathArray=new int[NumberOfVertices];
}

我有两个问题。

  1. 为什么一个简单的声明不允许WeightMatrix=new int[NumberOfVertices][NumberOfVertices]?我试着这么做,但有错误。我在网上找到了解决方案,但无法理解
  2. 初始化步骤不起作用。代码不会继续执行此语句WeightMatrix[NumberOfVertices][NumberOfVertices]={0};当我评论这一步时,一切都很好

问题#1:

WeightMatrix的类型为int**,因此无法使用new int[...]对其进行初始化。

正如您似乎已经在代码中修复的那样,正确的方法是用new int*[...]初始化它。

问题2:

只有在声明时才允许将数组初始化为值列表。例如:

int WeightMatrix[M][N] =
{
    {1,2,3,...},
    {4,5,6,...},
    ...
};

因此,您可以通过更改以下内容来修复编译错误:

WeightMatrix[NumberOfVertices][NumberOfVertices]={0};

对此:

for (int i=0; i<NumberOfVertices; i++)
    for (int j=0; j<NumberOfVertices; j++)
        WeightMatrix[i][j] = 0;

为什么不允许使用像WeightMatrix=new int[NumberOfVertices][NumberOfVertices]这样的简单声明?我试着这么做,但有错误。我在网上找到了解决方案,但无法理解。

将其与在堆栈上创建数组进行比较应该会有所帮助,您可以这样做:

int my_array[X][Y];

当您稍后说my_array[x][y]时,编译器对值Y的记录用于查找地址&my_array + x * Y + y处的int值。但是,当您使用new并在运行时指定维度时,编译器没有义务存储所涉及的维度——这会对运行时内存的使用和性能产生不利影响。但是,如果没有这样的维度,编译器就无法支持[x][y]表示法,因此将new当作创建多维数组来使用是有误导性的。在实践中,实现有时会将单个允许的数组维度存储在它们在使用new[]时要求的一些额外内存中,这样它们就可以迭代适当数量的元素来调用析构函数,但对于像int这样不需要破坏的类型,它们可能希望避免这种情况。

期望的是,您将计算出所需元素的总数:

int* weightMatrix = new int[NumberOfVertices * NumberOfVertices];

然后概念上的weightMatrix[x][y]可以存储在weightMatrix[x * NumberOfVertices + y](或者如果您更喜欢weightMatrix[x + NumberOfVertices * y])。

我建议编写一个简单的类,它有一个运算符来提供方便的表示法ala matrix(x, y):

template <typename T>
class Matrix
{
    Matrix(size_t X, size_t Y = X) : X_(X), Y_(Y), p_(new T[X * Y]) { }
    ~Matrix() { delete[] p_; }
    T& operator()(size_t x, size_t y) { return p_[x * Y + y]; }
    const T& operator()(size_t x, size_t y) const { return p_[x * Y + y]; }
    size_t X_, Y_;
    T* p_;
};

然后您可以编写更简单、更干净、更健壮的客户端代码:

Matrix matrix(20, 10);
matrix(4, 2) = 13;

您还可以很容易地在operator()中放入检查,以便在开发和测试期间捕获越界索引。