Varying size classes

• 12-09-2002
minesweeper
Varying size classes
For a project I am involved in, I have a 2D array representing a map. I want to create a class representing a zone on the map. There will be numerous zones on my map that will be different sizes, i.e. varying numbers of map array elements in each zone. What I have in mind is as follows:

Code:

``` class zone { private: int num_of_squares; int square_coordinates[num_of_squares][2]; //array giving map x and y coordinate for each square public: void set_squares(int a); void set_coordinates(int i, int pos_x, int pos_y); }zone1; void zone::set_squares(int a) { num_of_squares = a; } void zone::set_coordinates(int i, int pos_x, int pos_y) { square_coordinates[i][0] = pos_x; square_coordinates[i][1] = pos_y; } //here I call zone1.set_squares and zone1.set_coordinates to initialise all class variables```
Is what I have in mind possible? I am getting errors and I think it is to do with the non-constant nature of num_of_squares.

Any help would be much appreciated

Thanks
• 12-09-2002
OneStiffRod
Use a VECTOR or a Linked List. This gives you an array of varying size throughout the program - When you create an array it can only be of a constant size.
• 12-09-2002
master5001
It should work if number of_squares is set in the constructor, but I'm not a big fan of doing things this way. Not every compiler will compile this code correctly. You should just do dynamic allocation. You can do something like this in your set_squares function:

Code:

``` void zone::set_squares(int a) {     //assumes square_coordinates is an **int     num_of_squares = a;     square_coordinates = new *int[a];     for(;a--;)         square_coordinates[a] = new int[2]; } zone::~zone() {     for(;num_of_squares--;) {         delete[] square_coordinates[num_of_squares];     }     delete[] square_coordinates; }```

stupid smilies
[/edit]
• 12-09-2002
minesweeper
Excellent!! Thank you. Thought I might need to dynamically allocate but wasn't sure how to implement it.