Handling Huge Multidimensional Arrays in C++

前端 未结 8 1996
别那么骄傲
别那么骄傲 2021-01-24 19:15

I\'m designing a game in C++ similar to Minecraft that holds an enormous amount of terrain data in memory. In general, I want to store an array in memory that is [5][4][5][50][

8条回答
  •  别那么骄傲
    2021-01-24 19:54

    Below is how I understood what you showed you were trying to do in your example. I tried to keep it straightforward. Each Array of [50][50][50] is allocated in one memory chunk on the heap, and only allocated when used. There is also an exemple of access code. No fancy boost or anything special, just basic C++.

    #include 
    
    class Block
    {
        public:
        // Information about the blocks
        int data;
    };
    
    
    class Grid
    {
        public:
        bool empty;
        Block (*blocks)[50][50];
    
        Grid() : empty(true) {
        }
    
        void makeRoom(){
            this->blocks = new Block[50][50][50];
            this->empty = false;
        }
    
        ~Grid(){
            if (!this->empty){
                delete [] this->blocks;
            }
        }
    };
    
    
    class Parent
    {
        public:
        Grid (* child)[4][5];
    
        Parent()
        {
            this->child = new Grid[5][4][5];
        }
    
        ~Parent()
        {
            delete [] this->child;
        }
    };
    
    
    main(){
        Parent p;
        p.child[0][0][0].makeRoom();
        if (!p.child[0][0][0].empty){
            Block (* grid)[50][50] = p.child[0][0][0].blocks;
            grid[49][49][49].data = 17;
        }
    
        std::cout << "item = " 
                  << p.child[0][0][0].blocks[49][49][49].data 
                  << std::endl;
    }
    

    This could still be more simple and straightfoward and just use one bug array of [50][50][50][5][4][5] blocks in one memory chunk on the heap, but I'll let you figure out how if this is what you want.

    Also, usind dynamic allocation in class Parent only has the sole purpose to use heap instaed of stack, but for such a small array (5*4*5 pointers), allocating it on stack should not be a problem, hence it could be written.

    class Parent
    {
        public:
        Grid child[5][4][5];
    };
    

    without changing anything in the way it is used.

提交回复
热议问题