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

后端 未结 8 1315
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  清歌不尽
    2021-02-06 03:35

    are there other ways to define the 2D array?

    No without manipulating memory explicitely (malloc/free). If you use static allocated array (1st example) you allocate the space at compile time, so you can't add more rows or columns at runtime.

    The second example uses std::vector that hides to you dynamic memory allocation . This way you can eventually add more rows or columns at runtime.

    If you don't need to dynamically modify the array dimension, then the first solution is the simpler and faster one (even if I think that std::vector implementation is fast enough to be comparable to static array, more elegant and more object oriented).

    If you need to modify the array dimension at run-time use std::vector, because it saves you from dealing directly with malloc and free.

提交回复
热议问题