简体   繁体   中英

input vectors outside of main function c++

I am trying to get an input to a matrix by placing the whole thing as in a function outside of main (), as follows:

    void input_matrix(int row, int col){
std::vector<std::vector<int>> matrix;
  
  for (int m=0; m<row; m++){
    for (int n=0; n<col; n++){
      std::cin >> matrix[m][n];
    }
  }
  return matrix;
}

somehow the compiler doesn't like me inputing the matrix here, any solutions?

There are two errors in your code.

  1. The return type of the function input_matrix() is void which needs to be changed to vector<vector<int> >
  2. Initialize the matrix with proper space.

The corrected code would look something like this:

std::vector<std::vector<int> > input_matrix(int row, int col){
    std::vector<std::vector<int> > matrix(row, std::vector<int>(col));
  
    for (int m=0; m<row; m++){
        for (int n=0; n<col; n++){
            std::cin >> matrix[m][n];
        }
    }
    return matrix;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM