我正在尝试解决C++
中的Shortest Path问题。为此,我创建了以下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];
}
我有两个问题。
WeightMatrix=new int[NumberOfVertices][NumberOfVertices]
?我试过这样做,但有错误。我在网上找到了解决方案,但我无法理解。WeightMatrix[NumberOfVertices][NumberOfVertices]={0};
更进一步
当我评论这一步时一切正常。 答案 0 :(得分:1)
问题#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;
答案 1 :(得分:1)
为什么不允许使用
WeightMatrix=new int[NumberOfVertices][NumberOfVertices]
之类的简单声明?我试过这样做,但有错误。我在网上找到了解决方案,但我无法理解。
将它与堆栈中数组的创建进行比较应该会有所帮助,您可以这样做:
int my_array[X][Y];
当您稍后说my_array[x][y]
时,编译器的值Y
记录将用于查找地址int
的{{1}}值。但是,当您使用&my_array + x * Y + y
并在运行时指定维度时,编译器没有义务存储所涉及的维度 - 这会对运行时内存使用和性能产生负面影响。但是,如果没有这样的维度,编译器就不能支持new
表示法,因此误导您使用[x][y]
就像创建一个多维数组一样。在实践中,实现有时将单个允许的数组维度存储在他们使用new
时要求的一些额外内存中,以便他们可以迭代正确数量的元素来调用析构函数,但是他们可能希望避免对于类型这样的类型为new[]
,不需要破坏。
期望您将计算出所需元素的总数:
int
然后概念int* weightMatrix = new int[NumberOfVertices * NumberOfVertices];
可以存储在weightMatrix[x][y]
(或者您更喜欢weightMatrix[x * NumberOfVertices + y]
)。
我建议编写一个带有运算符的简单类,以提供方便的符号ala weightMatrix[x + NumberOfVertices * y]
:
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;
中,以便在开发和测试期间捕获越界索引。