zoukankan      html  css  js  c++  java
  • C++动态数组

    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];
           }

    这样就可以动态开辟空间,不用为长度不确定而烦恼了。

  • 相关阅读:
    qt运行编译按钮居然是灰色的
    suse linux服务器的常用命令
    windows 防火墙的bug
    烦恼核心
    System.Data.OleDb.OleDbException (0x80004005) 的问题
    c#利用批处理清理大目录
    Spider Studio 社区信息
    示例
    示例
    Spider Studio 新版本 (20140225)
  • 原文地址:https://www.cnblogs.com/qiuhaojie/p/5835510.html
Copyright © 2011-2022 走看看