Allocate memory for 2D array with C++ new[]

后端 未结 8 1381
情深已故
情深已故 2020-12-22 01:04

When I read some values from the user and I need to create an array of the specific size I do it somehow like this:

#include 
using namespace         


        
相关标签:
8条回答
  • 2020-12-22 01:46

    Although the "vector of vectors" solution can be satisfying, they are not a 2D structure: each "row" will be allocated independently of another, and length can be different row by raw (and hence the 2D constrain must be maintained manually: inserting an item requires all rows to be enlarged so that elemets that are one above the other maintain their relative position.

    In case you need a proper dynamic 2D structure, you can wrap a vector (simple mono-dimensional) in a class (let's call it "table") and provide that class with the operation requird to properly maintain it as an externally represented 2D. In particular:

    • Define a Colums() const and Rows() const functions retuning theactual size of the table.
    • Define a int& operator()(unsigned row, unsigned col) { return vect[row*Colums()+col]; } and it s const counterpart
    • Define a struct coord { unsigned r, unsigned c } and a convenient table::operator[](const coord&)
    • Define insert and remove methods to insert a row (just insert Colums() consecutive elements at r*Columns()) and a column (insert one element every Columns()+1 starting from c)
    • Define proper iterator classes that walk along colums (++ advance by 1 element) and rows (++ advance by Colums() elements) (Beware to consitently define an end() value for them)

    The key point of all this stuff is the understanding of the n = r*C+cformula at the second point. Everything else is just an almost immediate consequence.

    0 讨论(0)
  • 2020-12-22 01:50

    Anything that would look like a 2D-Array in code will not be a physical 2D array in memory, but either one plain block of memory or scattered, depending on how you allocate it.

    • You can torture yourself by doing dynamic allocation of N arrays in another dynamic array of N pointers, like nrussel's answer suggests.
    • You can make a vector of vectors instead, like billz and Arun C.B suggest - that would relieve you from managing the allocated memory yourself but still leave you with N+1 scattered allocations which is not very performant.
    • Brennan Vincent's answer suggests allocation of one dynamic array, containing a*b elements, which gives you one continuous block in memory. Combine that with the builtin dynamic memory management of std::vector he mentioned and be happy:

      std::vector<unsigned> matrix(a*b);

    If you want the matrix to be convenient to access, wrap the whole thing into a class providing you access to the elements with 2D-coordinates. But please step away from managing the memory yourself. It just hurts you and anyone who has to maintain that code (and search for mem leaks).

    0 讨论(0)
提交回复
热议问题