简体   繁体   English

使用所有条目初始化2d动态数组0

[英]Initializing a 2d dynamic array with all entries 0

is it possible to create a dynamic array with all entries in it equal to 0? 是否可以创建一个动态数组,其中所有条目均等于0?

 int** adjMatrix;
 adjMatrix= new int*[numOfVertices];
for(int i=0; i<numOfVertices; i++){
    adjMatrix[i]=new int[numOfVertices];
}

Also, I was asked to find the longest path in a graph. 另外,还要求我在图中找到最长的路径。 I was thinking about using Dijsktra's algorithm after multiplying all the weights with -1 and run the program in normal way. 在将所有权重乘以-1并以正常方式运行程序之后,我正在考虑使用Dijsktra的算法。 And then I'll multiply with -1 again and get the longest path. 然后我将再次与-1相乘并得到最长的路径。 I think this should give me the longest path, do you think it would work? 我认为这应该给我最长的途径,您认为这行得通吗? And also, I'm dealing with considerably big data, such as 1.000.000 nodes etc. and I have a time limit of 2 seconds and memory limit of 128mb. 而且,我正在处理相当大的数据,例如1.000.000节点等,并且我的时间限制为2秒,内存限制为128mb。 Can you suggest any other data structure instead of Adjacency Matrix? 您可以建议其他任何数据结构,而不是邻接矩阵吗? Because I'm pretty sure it will exceed the limits. 因为我很确定它将超出限制。 Any help would be much appreciated. 任何帮助将非常感激。

is it possible to create a dynamic array with all entries in it equal to 0? 是否可以创建一个动态数组,其中所有条目均等于0?

Use value initialization : 使用值初始化

for(int i=0; i<numOfVertices; i++){
    adjMatrix[i]=new int[numOfVertices]();
    //                                 ^^
}

The fastest way would be to use memset , but only if the array is contiguous in memory. 最快的方法是使用memset memset是该数组在内存中是连续的。 So, for this to work you should initially allocate a 1D array. 因此,要使其正常工作,您首先应该分配一维数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM