How to define a 2D array in C++ and STL without memory manipulation?

后端 未结 8 1491
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 03:14

There are several ways to define a 2D array in C++ and STL without memory manipulation, and the following codes illustrate two different methods:

int main () 
{
         


        
8条回答
  •  旧时难觅i
    2021-02-06 03:42

    A common pattern is encapsulating the 2D array inside a class that offers the appropriate interface. In that case, you can use other internal representations, like for example a single vector of rows*cols elements. The interface (usually operator()(int,int) will map the coordinates from the caller to a position in the linear vector.

    The advantage is that it has dynamic allocation, but a single allocation (unlike the std::vector> where each vector must acquire it's own memory) and in a single block providing locality of data.

提交回复
热议问题