如何使用pass-by-reference传递二维向量?

时间:2016-05-11 05:18:07

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

此代码是较大项目的一部分。我试图了解如何通过使用引用将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)
{
}

编辑:

对不起,我完全拙劣了。这是深夜,我忘了复制标题和声明。

2 个答案:

答案 0 :(得分:0)

这是乱码C ++语法。在对扫雷的调用中,您试图声明并初始化一个名为grid的变量。什么?您已经有一个名为grid的变量。只需获取C ++教科书并输入grid而不是vector< vector<int> > grid(col, vector<int>(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

答案 1 :(得分:0)

我看到的问题:

  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。之后你可以使用它。无需在grid的调用中添加用于声明minesweeper的代码。

相关问题