簡體   English   中英

C ++中的矩陣生成

[英]Matrix generation in C++

我有以下代碼:

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

現在我想要的是制作一個矩陣,該矩陣將具有按列逐個列出的num值。 例如, matrix[i][j] ,其中i來自,讓我們說“ 0到15”,“ j”也從“ 0到15”。 我希望他們將其放置為matrix[0][0] ,然后放置matrix[0][1]matrix[0][2]等,諸如此類:

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?
}

這是一些偽代碼..

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

注意:你必須做一些邊界檢查(例如,如果有更多的數字超過15 * 15,迭代row的增加將導致廢話...等等)

編輯:顯示,像普通數組一樣迭代,例如:

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;
}

標准“使用Boost”答案:

如果您只需要一個二維數組,請查看Boost.MultiArray

如果您需要進行線性代數,請查看Boost.uBlas

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM