|
++线程中经常会用到数组,在《C++程序设计第2版--谭浩强》中,还明确指出,定义数组时长度必须用常量表达式。 不过,这两天由于在开发一个C++工具,忽然发现,C++定义一维数组时,也可以用变量来定义长度了。
[附件已丢失]
int s=0; //代表房间数量 cout<<" lease input the number of rooms:"; cin>>s; int robotNum=0; //代表机器人数量 cout<<" lease input the number of robots:"; cin>>robotNum; int h=0; //代表冲突标识的数量 cout<<" lease 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就可以是任意变量了。 而对于二维数组,举个例子,创建矩阵out和in。
[附件已丢失]
int **out,**in; out=new int*[t]; in=new int*[t]; for(int f=0;f<t;f++){ out[f]=new int; in[f]=new int; }
[附件已丢失]
这样就可以动态开辟空间,不用为长度不确定而烦恼了。
#include "stdafx.h" #include <iostream> using namespace std; template <class T> class MyArray { int len; public: T *data; MyArray() { data = NULL; len = 0; } ~MyArray() { delete[] data; } T& operator [](int index); void push(T d); }; template <class T> T& MyArray<T>:  perator [](int index) { if(index<0||index>(len-1)) { cout<<"Bad subscript!"<<endl; exit(1); } return data[index]; } template <class T> void MyArray<T>::push(T d) { T *pdata = data; data = new T[len + 1]; if(pdata != NULL) { for(int i = 0 ; i < len ; i++) { data = pdata; } delete[] pdata; } data[len] = d; len++; } //测试代码 int main(int argc, char* argv[]) { MyArray<int> a; a.push(11); a.push(22); a.push(33); a.push(55); a[0]=44; cout<<a[0]<<endl<<a[1]<<endl<<a[2]<<endl<<a[3]<<endl; return 0; }
使用new动态分配存储空间 2 3 #include<iostream> 4 using std::cout; 5 6 int main() 7 { 8 // 第1种方式 9 int *a=new int;10 *a=1;11 cout<<"使用第一种方式进行动态分配存储空间的结果为:\n"12 <<"*a= "<<*a<<std::endl;13 delete a; // 释放动态存储空间14 // 第2种方式15 int *b=new int(2);16 cout<<"使用第一种方式进行动态分配存储空间的结果为:\n"17 <<"*b= "<<*b<<std::endl;18 delete b; // 释放动态存储空间19 // 第3种方式20 int *c;21 c=new int(3);22 cout<<"使用第一种方式进行动态分配存储空间的结果为:\n"23 <<"*c= "<<*c<<std::endl;24 delete c; // 释放动态存储空间25 26 // 动态创建数组27 float *d=new float [3];28 d[0]=3;29 d[1]=6;30 d[2]=8;31 cout<<"d[0]= "<<d[0]<<std::endl;32 d=d+1; //数组名和指针之间的根本区别33 cout<<"d[0]= "<<d[0]<<std::endl;34 d=d-1;35 cout<<"d[0]= "<<d[0]<<std::endl;36 delete [] d; // 释放动态存储空间37 return 0;38 }
[附件已丢失]
[附件已丢失]
|