【问题标题】:How to pass a 2d vector using pass-by-reference?如何使用传递引用传递二维向量?
【发布时间】:2016-09-06 07:46:37
【问题描述】:

此代码是一个更大项目的一部分。我试图了解如何通过使用引用将 2d 向量传递给另一个函数。这是我当前的代码,我无法弄清楚错误是什么(使用 Xcode)。

代码:

int main()
{
   int mines, col, row;

   int test;

   cout << "\nHow many many rows of boxes?" <<endl; //getting row, 
   //column and mines from user

   cin >> row;
   cout << "\nHow many many columns of boxes?" <<endl;
   cin >> col;
   cout << "\nHow many many mines are in the board?" <<endl;
   cin >> mines;

   test=(row*col)-1;        // test to make sure that the whole gameboard is not filled with mines (multiplies row and columns and subtracts by 1)
   while (!(test>= mines))  // if there are more mines than cells or if the whole board is filled with mines, will ask for mines again
   {
      cout << "\nHow many many mines are in the board?" <<endl;
      cin >> mines;
   }

   vector <vector<int> > grid(col, vector<int>(row));   //create 2d vector with col and row as parameters

   minesweeper(row, col, mines, vector< vector<int> > grid(col, vector<int>(row)))  //sends all data to minesweeper();




   return 0;
}

void minesweeper(int row,
                 int col,
                 int numOfMines,
                 vector<vector<int>>& mineField)
{
}

编辑:

对不起,我完全搞砸了这个问题。那是深夜,我忘了复制标题和声明。

【问题讨论】:

    标签: c++ xcode vector 2d pass-by-reference


    【解决方案1】:

    这是乱码的 C++ 语法。在对 minesweeper 的调用中,您尝试声明和初始化一个名为 grid 的变量。什么?您已经有一个名为 grid 的变量。只需获取 C++ 教科书并输入 grid 而不是 vector&lt; vector&lt;int&gt; &gt; grid(col, vector&lt;int&gt;(row)) 就可以了

    vector <vector<int> > grid(col, vector<int>(row));  //create 2d vector with col and row as parameters
    
    minesweeper(row, col, mines,  grid);
    

    之后它是通过引用传递的,因为您已经特别声明了参数以使其通过引用。您是否看到 mineField 参数与其他参数有什么不同,这会使其特别标记为通过引用传递?

    并考虑将描述行数的变量命名为rows 而不是row

    【讨论】:

      【解决方案2】:

      我看到的问题:

      1. 在调用函数minesweeper 之前,您还没有声明它。在main前添加声明。

        void minesweeper(int row,
                         int col,
                         int numOfMines,
                         vector<vector<int>>& mineField);
        
      2. 您没有使用正确的语法来调用该函数。使用:

        minesweeper(row, col, mines, grid)  //sends all data to minesweeper();
        

        您已经在该行之前声明了grid。之后你就可以使用它了。无需在对minesweeper的调用中添加用于声明grid的代码。

      【讨论】:

        猜你喜欢
        • 2020-06-10
        • 2013-03-22
        • 2018-10-15
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        相关资源
        最近更新 更多