bijlikamasla
bijlikamasla

Reputation: 371

Matrix generation in C++

I have the following code:

for (int w=0; w<10; w++)
{
    //some lines of code
    unsigned long num = x.to_ulong(); 
    cout << "Decimal form is: " << num << endl;
}  

Now what I want is, to make a matrix which will have these values of num, column wise. For example, matrix[i][j], where i is from, let's say "0 to 15", and "j" is from "0 to 15" as well. I want them to put like, matrix[0][0], then matrix[0][1], matrix[0][2] and so on, something like:

for(int i=0; i<=15; i++)
{
    for(int j=0; j<=15; j++)
        matrix[i][j] = num //here is problem, value of "num" what shall i write instead of it?
}

Upvotes: 0

Views: 1009

Answers (2)

Emile Cormier
Emile Cormier

Reputation: 29229

Standard "use Boost" answer:

If you just need a two-dimensional array, check out Boost.MultiArray.

If you need to do linear algebra, check out Boost.uBlas.

Upvotes: 0

Nim
Nim

Reputation: 33655

Here is some pseudo code..

std::vector<std::vector<unsigned long> > matrix(15); // 15 rows
typedef std::vector<std::vector<unsigned long> >::iterator it_type;

it_type row = matrix.begin();

for (int w=0;w<10;w++)
{
  //some lines of code
  unsigned long num = x.to_ulong(); 
  cout <<"Decimal form is: " << num<< end;
  // if we've hit 15 items in the current row (i.e. 15 columns), then shift to the next row
  if (row->size() == 15)
    ++row;

  // add this to the next column in the current row
  row->push_back(num);
}
// resize the last row
row->resize(15); // this will ensure that there are 15 columns in the last row

NOTES: you'll have to do some bounds checking (for example if there are more numbers than 15 * 15, the incrementing the iterator row will lead to crap... etc.)

EDIT: to display, iterate through like a normal array, for example:

for(size_t i=0; i < matrix.size(); ++i)
{
  for(size_t j=0; j < matrix[i].size(); ++j)
    cout << matrix[i][j] << " ";
  cout << endl;
}

Upvotes: 2

Related Questions