std::vector and contiguous memory of multidimensional arrays

后端 未结 6 1809
青春惊慌失措
青春惊慌失措 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:01

    As @Als already pointed out, yes, std::vector (now) guarantees contiguous allocation. I would not, however, simulate a 2D matrix with an array of pointers. Instead, I'd recommend one of two approaches. The simpler by (by far) is to just use operator() for subscripting, and do a multiplication to convert the 2D input to a linear address in your vector:

    template 
    class matrix2D { 
         std::vector data;
         int columns;
    public:
         T &operator()(int x, int y) {
             return data[y * columns + x];
         }
    
         matrix2D(int x, int y) : data(x*y), columns(x) {}
    };
    

    If, for whatever reason, you want to use matrix[a][b] style addressing, you can use a proxy class to handle the conversion. Though it was for a 3D matrix instead of 2D, I posted a demonstration of this technique in previous answer.

提交回复
热议问题