user1060993
user1060993

Reputation: 55

setting all values in a dynamic 2 d array to a set value

I have to setup a dynamic 2 D array that is x Number of rows by y number of columns. This array has been declared as an enumerated type and I want to initialize all values to a known value of EMPTY. Is there a way to do this with a single command or do I need to loop through each row/column abd set it up that way. I know static arrays can be done as Array[][] = {EMPTY} but I cannot get this method to work.

status ** seats;

seats = new status* [NO_OF_ROWS];// declare array with NO_OF_ROWS
for (row = 0; row < NO_OF_ROWS; row++)
   seats[row] = new status[NO_OF_SEATS]; 

Upvotes: 1

Views: 931

Answers (3)

Saeed All Gharaee
Saeed All Gharaee

Reputation: 1693

Why don't you use vector instead? Although its syntax seems to be frightening, after understanding the logic it would be easy.

Firstly add vector library:

#include <vector>

Here is how to declare a 2D vector:

vector<vector<int> > array(4,vector<int>(3));

Now array is a vector with 4 cells and each cell is a vector with 3 cells, In other words array is 2D.

Ok. Here is how to assign all cells to -1:

vector<vector<int> > array(4,vector<int>(3,-1));

I wish it could help.

Upvotes: 0

Martin
Martin

Reputation: 141

You could try using memset - as you know, arrays in C are internally defined as a contiguous memory block. memset, on the other hand, is a function which fills a certain memory block with a certain value.

Now, since your bi-dimensional array is not contiguous (because you have an array of pointers), you won't be able to call 'memset' just once, but at least you can call it for every row, meaning you'll call it NO_OF_ROWS times.

It should be similar to this (note that some casting may be required, and also my c++ is a little rusty):

for (row = 0; row < NO_OF_ROWS; row++)
{
    seats[row] = new status[NO_OF_SEATS]; 
    memset(seats[row],EMPTY,NO_OF_SEATS*sizeof(status));
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477600

Yes:

#include <vector>

typedef std::vector< std::vector<status> > seat_type;

seat_type seats(NO_OF_ROWS, std::vector<status>(NO_OF_SEATS));

// now use seats[i][j] etc.

In C++, a "dynamic array" is called std::vector.


If you want to avoid many dynamic allocations, you could alternatively make a single vector

std::vector<status> seats(NO_OF_ROWS * NO_OF_SEATS);

and access it in strides, i.e. the (i,j)th seat is seats[j + NO_OF_SEATS * i].

Upvotes: 3

Related Questions