如何在C 中打印网格向量

How to print a grid vector in C++

本文关键字:打印 网格 向量      更新时间:2023-10-16

我正在网格中的C 打印向量。在这里,我需要将随机数放入3x * 3y的矢量大小。然后,我必须用一个阵列用二维矩阵将它们打印出来。我不明白如何用一个数组表示二维矩阵。此外,我不确定如何打印多维向量。我必须处理print_vector函数,该功能以网格形式打印向量。您能帮我下面改进此代码吗?

int main()
{
  populate_vector();
  return 0;
}
void populate_vector()
{
  int x,y;
  cout<<"Enter two Vectors x and y n->";
  cin>> x;
  cin>> y;
  srand((unsigned)time(NULL));
  std::vector<int> xVector((3*x) * (3*y));
  for(int i = 0; (i == 3*x && i == 3*y); ++i){
    xVector[i] = rand() % 255 + 1;
       if(i == 3*x){
         cout << "n";
       }
  }
  print_vector(xVector);
}
void print_vector(vector<int> &x) {

}

我不是专家,但我喜欢只有一个向量。

void print_vector(vector<vector<int>>& m_vec)
{
    for(auto itY: m_vec)
    {
        for(auto itX: itY)
            cout << itX << " ";
        cout << endl;
    }
}
void populate_vector()
{
    int x,y;
    cout << "Enter Two Vectors x and y n ->";
    cin >> x;
    cin >> y;
    srand((unsigned)time(NULL));
    vector<vector <int>> yVector;
    for(auto i = 0; i < y*3; ++i)
    {
        vector<int> xVector;
        for(auto j = 0; j < x*3; ++j)
            xVector.push_back(rand()%255+1);
        yVector.push_back(xVector);
    }
    print_vector(yVector);
}

编辑:哦,我以前从未见过这个网站,谢谢Saykou ...这是有效的代码:http://cpp.sh/3vzg

类似的东西会阐明您的代码,在一个过程中填充了向量,而另一个则打印了向量

int main()
{
    int x,y;
  std::cout<<"Enter two Vectors x and y n->";
  std::cin>> x;
  std::cin>> y;
  srand((unsigned)time(NULL));
  int xSize = x * 3; // it is important to have the size of the final grid stored
  int ySize = y * 3; // for code clarity 
  std::vector<int> xVector( xSize * ySize);
  // iterate all y 
  for ( y = 0 ; y < ySize; ++y) {
      // iterate all x 
    for ( x = 0 ; x < xSize;  ++x) {
      // using row major order https://en.wikipedia.org/wiki/Row-_and_column-major_order
        xVector[y * xSize + x]  = rand() % 255 + 1;
    }
  }
  // when printing you want to run y first 
  for ( y = 0 ; y < ySize; ++y) {
    for ( x = 0 ; x < xSize;  ++x) {
      // iterate all y 
        printf("%d ", xVector[y * xSize + x] );
    }
    printf("n");
   }
}

我认为您想注意这一步骤,在这里您可以将X和Y位置转换为一个阵列维度。很简单,您只需要将y乘以x的大小并添加x即可。

所以在二维中这样的东西

1 2 3 
4 5 6 

最终将进入类似的东西

1 2 3 4 5 6

您可以看到它在这里运行