简体   繁体   English

2D矩阵声明差异

[英]2D Matrix declaration differences

I noticed something strange about my code, and the amount of time it was taking to declare and initialize a 2D matrix of mine. 我注意到我的代码有些奇怪,以及声明和初始化我的2D矩阵花费的时间。

First way : 第一种方式

vector< vector<double> > gblStiff(dOF, vector<double>(dOF, 0));

dOF was some determined value earlier in the code. dOF是代码中较早的确定值。 This first way took approximately 3 seconds when dOF = 30000!! 当dOF = 30000时,这第一种方法花费了大约3秒钟!

Second way : 第二种方式

double** gblStiff = new double*[dOF];
for (i=0; i < dOF; i++) 
    gblStiff[i] = new double[dOF];

This second way takes 0.063 seconds for the same dOF!! 对于相同的dOF,第二种方法需要0.063秒!!

Anyone able to shed light onto why this is happening? 任何人都可以弄清为什么会这样吗? I am extremely curious. 我很好奇。

This is really a C++ question. 这确实是一个C ++问题。 First, you probably didn't compile with optimisation. 首先,您可能没有对优化进行编译。 The vector template really needs a little compiler help to be usable. vector模板确实需要一点编译器帮助才能使用。 Second, vector 's constructor initialises all of the elements; 其次, vector的构造函数初始化所有元素。 in your case, it initialises dOF*dOF double s to zero. 在您的情况下,它将dOF*dOF double s初始化为零。 new double[dOF] does no such thing; new double[dOF]new double[dOF] that memory can contain anything at all. 该内存可以包含任何内容。

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

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