繁体   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