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

后端 未结 8 1399
情深已故
情深已故 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题