初始化不起作用
Initialization not Working
我正在尝试解决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];
}
我有两个问题。
- 为什么一个简单的声明不允许
WeightMatrix=new int[NumberOfVertices][NumberOfVertices]
?我试着这么做,但有错误。我在网上找到了解决方案,但无法理解 - 初始化步骤不起作用。代码不会继续执行此语句
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()
中放入检查,以便在开发和测试期间捕获越界索引。
- 为什么 zlib 放气初始化调用一次不起作用?
- 内部结构初始化不起作用 - C++
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 初始化 std::initializer_list 通过 std:: 初始化 std::p air 在初始化 std::array 时不起作用?
- 没有临时数组的列表初始化 - 在 GCC 中不起作用
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- <int> 具有初始化的矢量工厂不起作用
- 初始化矢量的大小,否则附加不起作用,为什么
- MEMSET FUCTION在我的C 动态阵列初始化中不起作用
- 操作员=超载不起作用,除非对象已经初始化
- 使用初始化列表的 POD 类型初始化不起作用
- 使用数据初始化 cv::Mat 不起作用
- POD变量的直接初始化不起作用,但当将变量推到向量上时,复制初始化起作用
- 为什么类构造函数在通过复制初始化对象时不起作用
- 为什么用double&&初始化对象方法不起作用?
- 尝试使用值初始化列表,但在使用变量创建大小时不起作用
- GCC 4.8.1 中的C++11:复制构造函数的列表初始化不起作用
- 在 C++11 中初始化 std::vector<std::string>不起作用?
- 为什么这种初始化不起作用
- 初始化程序列表作为容器不起作用