std::vector and contiguous memory of multidimensional arrays

后端 未结 6 1820
青春惊慌失措
青春惊慌失措 2020-11-27 07:42

I know that the standard does not force std::vector to allocate contiguous memory blocks, but all implementations obey this nevertheless.

Suppo

6条回答
  •  鱼传尺愫
    2020-11-27 08:12

    A simple class to create, as you call it, a 2D array, would be something like:

    template  2DArray {
    private:
        T *m_data;
        int m_stride;
    public:
        2DArray(int dimY, int dimX) : m_stride(dimX) : m_data(new[] T[dimX * dimY]) {}
        ~2DArray() { delete[] m_data; }
        T* operator[](int row) { return m_data + m_stride * row; }
    }
    

    It's possible to use this like:

    2DArray myArray(30,20);
    
    for (int i = 0; i < 30; i++)
        for (int j = 0; j < 20; j++)
            myArray[i][j] = i + j;
    

    Or even pass &myArray[0][0] as address to low-level functions that take some sort of "flat buffers".

    But as you see, it turns naive expectations around in that it's myarray[y][x].

    Generically, if you interface with code that requires some sort of classical C-style flat array, then why not just use that ?

    Edit: As said, the above is simple. No bounds check attempts whatsoever. Just like, "an array".

提交回复
热议问题