C ++ 2D dynamic array

I am trying to dynamically assign a 2d array to a pointer in constructor initialization.

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
int **_array;

However, this does not work. I understand that multidimensional arrays are distributed somewhat differently. Can anyone explain this with an explanation?

Thanks in advance.

+3
source share
5 answers

Some answers here say that a 2-dimensional array is an array of pointers to other arrays. This is not the case (where to store pointers if all you select is array data !?). Instead, a 2-dimensional array is an array of other arrays. Thus, you will have to change the type of your member:

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
int (*_array)[10];

, new[] . 10 , , , . , temlate ( boost::identity).

template<typename T> struct identity { typedef T type; };

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
identity<int[10]>::type *_array;

typedef. , new[], delete[], .

new[] , , , ( ) - , . , , , .

, , . , .

+7

2- C .

, 3x3 a ( int**):

a[0] (a[0] is of type int*) = [0][1][2]
a[1] (a[1] is of type int*) = [0][1][2]
a[2] (a[2] is of type int*) = [0][1][2]

, , (int **), .

, :

int** a = new int*[10];

a, :

for(int i=0; i<10; ++i)
    a[i] = new int[10];

++.

, , , 10 * 10 2D ( "" ):

const int ARRAY_WIDTH = 10;
const int ARRAY_HEIGHT = 10;
int* a = new int[ARRAY_WIDTH * ARRAY_HEIGHT];

    // To access a[5][2] you would use: 
a[5 + (2 * ARRAY_WIDTH)] = 0;
+4
int **array  = new int *[10];

for(int i= 0; i< 10;i++)
{
    array[i] = new int[10];
}
+3

, .

int **Array;
Array = new int*[10];
for (int i = 0; i < 10; i++) {
    Array[i] = new int[10];
}
0

, :

//vec2d.h
#include<vector>

template<class T>
void init2DVect(std::vector< std::vector<T> >& _T, size_t sx, size_t sy)
{
  _T.resize( sx );
  for(size_t i =0; i < sx; ++i)
  {
    std::vector<T> ins_v(sy);
    _T[i] = ins_v;
  }
}

:

//file: vec2d_test.cpp
#include "vec2D.h"

#include<cassert>

int main()
{
  std::vector< std::vector<int> > vi;
  size_t sx = 5;
  size_t sy = 7;
  init2DVect(vi, sx, sy);

  for(size_t i = 0; i < sx; ++i)
  {
    for(size_t j = 0; j < sy; ++j)
    {
      vi.at(i).at(j) = i*j;
    }
  }

  for(size_t i = 0; i < sx; ++i)
  {
    for(size_t j = 0; j < sy; ++j)
    {
      assert( vi.at(i).at(j) == i*j );
      assert( vi[i][j] == i*j );
    }
  }   

  return 0;
}

This has the advantage that you don't have to worry about memory, and you can use the vector :: at () function to throw an exception if you are outside the borders ... good for C ++ homework, but the std vector :: vector should not be the fastest way to do this.

Otherwise, the TNT library does the trick.

0
source

Source: https://habr.com/ru/post/1733482/


All Articles