Ava
Ava

Reputation: 6053

Accessing values from a two dimensional initialized array

int a[][30]={{2, 16},{4, 8},{5, 16, 21},{2,6,3,5,6}};

Since the size of the second dimension is varying. If I want to access something like for a particular value of i(first dimension), access all j values(2nd dimension), how do I write that statement?

What I thought was:

for(int j=0;j<30;j++)
  a[i][j]=some operation;

but its unnecessarily looping till 30 which is the max value. What's the efficient way to do it?

Thanks.

Upvotes: 0

Views: 277

Answers (2)

aschepler
aschepler

Reputation: 72473

The compiler does not keep any information about how many values were in the braced initializer. Instead, it fills the "missing" values with zeros.

So these two are equivalent:

int a[][4] = {{2, 16},{4, 8, 5}};
int a[][4] = {{2, 16, 0, 0}, {4, 8, 5, 0}};

If you know that none of the "actual" data elements are zero, you can stop your loop when you find a zero element. Otherwise, you'll need to set up the data differently.

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507433

The size of both dimensions is fixed. The outer dimension has size 4 and the inner has size 30.

If you iterate over the inner dimension, then you will print lots of zeros, as that is what you initialize the remaining integers that aren't explicitly initialized to.

You seem to want this:

std::vector<int> a[] = { 
   boost::list_of(2)(16), 
   boost::list_of(4)(8), 
   boost::list_of(5)(16)(21), 
   boost::list_of(2)(6)(3)(5)(6) 
};

Upvotes: 2

Related Questions