How to declare a 2D array inside a class in C ++?

I want to declare a 2D array inside a class. The size of the array will be initialized in the constructor. In Java, I can perform this operation as

public class A {
  public int[][] indices;

  A(int a,int b){
     indices = new int[a][b];
  }
}

How can I perform the same operation in C ++?

+4
source share
4 answers

Use the vector of vectors:

std::vector<std::vector<squares>> squares;

And initialize the constructor:

squares.resize(xPos);
for (int i = 0; i < xPos; i++) {
    squares[i].resize(yPos);
}
+3
source

In C ++, a more popular way for a 2D array is to use a 2D vector. This will have many benefits.

  • You can also access items through [][].
  • The size is dynamically distributed - so you can always increase the size with myVector.push_back(vec)or myVector[i].push_back(x).

, - ArrayList Java.

, ,

#include <vector>
public class A {
    std::vector<std::vector<int>> indices;
    //...
}
+2

, - . . , , . , . uBLAS, . :

int main () {
    using namespace boost::numeric::ublas;
    matrix<double> m (3, 3);
    for (unsigned i = 0; i < m.size1 (); ++ i)
        for (unsigned j = 0; j < m.size2 (); ++ j)
            m (i, j) = 3 * i + j;
    std::cout << m << std::endl;
}
+1

, , ++

class C {
    int** someArray;
    public: 
        C() {
            someArray = new int*[ SIZE_GOES_HERE ];
            for( unsigned int j = 0; j < SIZE_GOES_HERE; ++j )
                someArray[ j ] = new int[ SECOND_SIZE ];
        }
};

,  , , , , , 2d-.

0

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


All Articles