1

I am very new to C++ so please forgive my ignorance and ineptness.

I am trying to create a class called Planet. Every planet will have a width and height (they are stored as rectangles because I'm not a complete masochist). Different planets have different widths and heights.

The class therefore needs member variables to store these values. It also needs a number of arrays to store terrain information and the like. The size of these arrays should be determined by the value of the width and height variables. So each object would have different-sized arrays. My problem is: how can I declare these arrays within the class?

Trying to declare arrays using member variables simply doesn't work:

class planet
{
public:
    planet();   // constructor
    ~planet();  // destructor

    // other public functions go here


private:

    int width;   // width of global map
    int height;  // height of global map

    int terrainmap [width][height]; 
};

This causes the error "Invalid use of non-static data member 'height'", which makes sense as obviously the compiler doesn't know how big that array should be. This also applies if I make them static variables.

I have tried doing it with vectors instead, since they are more flexible:

vector<int> terrainmap[width][height];

But I get exactly the same error.

I suppose I could just initialise an array or vector with the largest possible values for width/height, but that seems wasteful if some objects in this class will have smaller values and therefore won't be using the whole array. Is there an elegant solution to this?

JonathanCR
  • 11
  • 2
  • 1
    Can you show what your tried with a vector? That is the route you should take. – NathanOliver Jul 09 '19 at 16:15
  • Check this question https://stackoverflow.com/questions/2076624/c-matrix-class . Sadly there is no standard matrix class in `C++` (https://www.quora.com/Why-are-there-no-matrix-libs-in-C++-standard-libs) – Renat Jul 09 '19 at 16:19
  • its the wrong syntax, you need to write vector< vector > terrainMap; – AndersK Jul 09 '19 at 16:22

1 Answers1

0

You are better off using std::vector. In order to represent a 2-dim array, you can use a vector of vectors, hence the declaration you see below. You can even reserve the necessary space but it must be done in the constructor.

class planet
{
public:
    planet(int width, int height): width(width), height(height) {
        terrainmap.reserve(width);
        for(int i=0; i<width; ++i) {
            terrainmap[i].reserve(height);
        }
    }
    ~planet() = default;  // destructor

    // other public functions go here


private:

    int width;   // width of global map
    int height;  // height of global map

    std::vector< std::vector<int> > terrainmap;
};

Of course, reservation is not strictly necessary but if the object is large and you're constantly pushing new objects into terrain map, reservation will save you some re-allocation of memory.

Kon
  • 4,023
  • 4
  • 24
  • 38