简体   繁体   中英

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

I want to declare a 2D array within 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++?

Use a vector of vectors:

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

And initialize in constructor:

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

In c++ a more popular way for a 2D array would be to use a 2D vector. This would have many advantages.

  1. You could also access on elements via [][] .
  2. The size is dynamically allcoated - so you could always increase the size by a myVector.push_back(vec) or myVector[i].push_back(x) .

To shortly describe it, it is something like an ArrayList in Java .

So maybe use a

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

As there are already solutions to your answer, i would suggest something different. Dealing with 2D or multi-D arrays. I think pointers are much faster than vectors. You can always argue that we should make the best use of technology. But then i would suggest you to use a library called uBLAS which makes processing of arrays easy. The docs can be found here and use it like:

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;
}

You can declare a raw array like so in C++ class

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 ];
        }
};

Just remebr to mange the memry later What this does is declare a double pointer which will poin at an array of pointers which will point at arrays creating a 2d array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM