C++線程中經常會用到數組,在《C++程序設計第2版--譚浩強》中,還明確指出,定義數組時長度必須用常量表達式。
不過,這兩天由於在開發一個C++工具,忽然發現,C++定義一維數組時,也可以用變量來定義長度了。
int s=0; //代表房間數量 cout<<"Please input the number of rooms:"; cin>>s; int robotNum=0; //代表機器人數量 cout<<"Please input the number of robots:"; cin>>robotNum; int h=0; //代表沖突標識的數量 cout<<"Please input the number of conflict markings:"; cin>>h; int m=robotNum*s; CTree tr[robotNum];
部分開發代碼,最后一行正常運行。
不過用的較多的還是動態數組啦,因為項目中有很多結構體,結構體里面又有數組,數組的長度也不確定的情況下,這里面的數組就用動態開辟的方法了。
typedef struct CTNode{ int *M; int preT; //進入該結點的變遷的編號 CTNode *firstChild; CTNode *nextSibling; CTNode *parent; }CTNode,*CTree;
定義指針M的目的就是為了動態地創建數組。
CTree c=new CTNode; c->M=new int[s];
s就可以是任意變量了。
而對於二維數組,舉個例子,創建矩陣out和in。
int **out,**in; out=new int*[t]; in=new int*[t]; for(int f=0;f<t;f++){ out[f]=new int[s]; in[f]=new int[s]; }
這樣就可以動態開辟空間,不用為長度不確定而煩惱了。