I have a C++ class with a member that is supposed to be a two dimensional array. I want to declare my array as a member in the header file of the class. Then in the constructor of my class I want to initialize my array with a size (given to the constructor) and fill it with zeros.
I have a working example of what I want in java:
class Obj {
int[][] array;
public Obj(int sizex, int sizey) {
array = new int[sizex][sizey];
}
}
public class Main
{
public static void main(String[] args) {
Obj o = new Obj(12,20);
}
}
I do not want to mess with pointers or alloc() and free(). As my class is supposed to be basically a wrapper for this array, I want to keep it simple.
I have thought about using std::vector, but as the array is never being resized after its initialization, I feel like vector is a little overpowered... Is there a better way than this: ?
#include<vector>
class Obj {
std::vector<std::vector<int>> array;
public:
Obj(int xsize, int ysize) {
std::vector<std::vector<int>> newArray(xsize, std::vector<int>(ysize, 0));
array = newArray;
}
};
int main()
{
Obj o(12,20);
}
std::vector
is the best match here. (As you said, in most cases raw arrays and pointers could be avoided. Also see How can I efficiently select a Standard Library container in C++11? )
And you can initialize the data member directly in member initializer list instead of assigning in the constructor body after default-initialization, eg
Obj(int xsize, int ysize) : array(xsize, std::vector<int>(ysize, 0)) {
}
Other than using std::vector you can just allocate memory of the required size from the heap.
class Obj {
int** arr;
int x, y;
public:
Obj(int sizex, int sizey) : x(sizex), y(sizey) {
arr = new int*[sizex];
for (unsigned i = 0; i < sizex; i++) {
arr[i] = new int[sizey];
}
}
//IMPORTANT TO DELETE, OTHERWISE YOU'LL GET A MEMORY LEAK
~Obj() {
for (unsigned i = 0; i < x; i++) {
delete[] arr[i];
}
delete[] arr;
}
}
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.