简体   繁体   中英

Indexing to a std::vector with X,Y,Z

I have a std::vector<Chunk*> m_vpChunks object, that holds a vector of chunks. Also i have a world and X,Y,Z coordinates.

I create chunks with:

// Go through all chunks
    for(int x = 0; x < m_iSize; x+=CHUNK_SIZE_X)
    {
        for(int y = 0; y < m_iSize; y+=CHUNK_SIZE_Y)
        {
            for(int z = 0; z < m_iSize; z+=CHUNK_SIZE_Z)
            {


                // Create new chunk
                CChunk  *pChunk =   NULL;
                pChunk          =   new CChunk(CVector3(x,y,z));
                assert(pChunk);       


                // Add it to our list
                m_vpChunks.push_back(pChunk);

            }
        }
    }

And want to index into a chunk vector with X,Y,Z like:

CChunk *GetChunk(int X, int Y, int Z)
{

 return m_vpChunks[ *** ];

}

Any ideas?

I think it is:

return m_vpChunks[
  x/CHUNK_SIZE_X * (m_iSize/CHUNK_SIZE_Y * m_iSize/CHUNK_SIZE_Z) +
  y/CHUNK_SIZE_Y * (m_iSize/CHUNK_SIZE_Z) +
  z/CHUNK_SIZE_Z ];


But seriously, use a different data structure. Nested vectors come to mind, in which case you'd return:

 return m_vpChunks[x][y][z]; 

or maybe

 return m_vpChunks[x/CHUNK_SIZE_X][y/CHUNK_SIZE_Y][z/CHUNK_SIZE_Z]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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